Java always passes arguments by value NOT by reference.


Let me explain this through an example:

public class Main{
public static void main(String[] args){
Foo f = new Foo("f");
changeReference(f); // It won't change the reference!
modifyReference(f); // It will modify the object that the reference variable "f" refers to!
}
public static void changeReference(Foo a){
Foo b = new Foo("b");
a = b;
}
public static void modifyReference(Foo c){
c.setAttribute("c");
}
}

I will explain this in steps:

  1. Declaring a reference named f of type Foo and assign it to a new object of type Foo with an attribute "f".

    Foo f = new Foo("f");

  2. From the method side, a reference of type Foo with a name a is declared and it's initially assigned to null.

    public static void changeReference(Foo a)

  3. As you call the method changeReference, the reference a will be assigned to the object which is passed as an argument.

    changeReference(f);

  4. Declaring a reference named b of type Foo and assign it to a new object of type Foo with an attribute "b".

    Foo b = new Foo("b");

  5. a = b is re-assigning the reference a NOT f to the object whose its attribute is "b".


  6. As you call modifyReference(Foo c) method, a reference c is created and assigned to the object with attribute "f".

  7. c.setAttribute("c"); will change the attribute of the object that reference c points to it, and it's same object that reference f points to it.

I hope you understand now how passing objects as arguments works in Java :)

最新文章

  1. vue vue-cli安装
  2. Qt线程(4) 降低线程占用CPU
  3. php数组插入数据库这个功能该怎么实现
  4. Swift学习--常量.变量.数据类型的使用(一)
  5. 【转载】COM多线程原理与应用
  6. 持久化消息队列memcacheq的安装配置
  7. Oracle EBS-SQL (PO-11):检查采购订单退货数.sql
  8. while循环与i--
  9. 关于SELECT LAST_INSERT_ID()的使用规则
  10. kubernetes之监控Prometheus实战--prometheus介绍--获取监控(一)
  11. SDKmanager的位置
  12. js中浅拷贝和深拷贝以及深拷贝的实现
  13. Http协议中get和post的区别
  14. js替换字符中的斜杠反斜杠
  15. C# 实体/集合差异比较,比较两个实体或集合值是否一样,将实体2的值动态赋值给实体1(名称一样的属性进行赋值)
  16. 第三十二篇-NavigationView导航抽屉的使用
  17. Docker技术底层架构剖析
  18. plt实现动态画图
  19. 阿里云php-7.2.12 安装
  20. C#获取一个数组中的最大值、最小值、平均值

热门文章

  1. C++实现VPN工具之VPN错误代码大全
  2. iOS FMDB 不需要关闭
  3. Linux下安装Django
  4. JAVA中的Calendar得到当前时间的年份、月份、日期
  5. 【python】Head First Python(五)
  6. HDU 4793 Collision (解二元一次方程) -2013 ICPC长沙赛区现场赛
  7. JS调用自定义弹窗【bootstrap】
  8. <context-param>与<init-param>
  9. October 5th 2016 Week 41st Wednesday
  10. iOS 动态计算文本内容的高度