Java学习随笔1:Java是值传递还是引用传递?
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:
Declaring a reference named
f
of typeFoo
and assign it to a new object of typeFoo
with an attribute"f"
.Foo f = new Foo("f");
From the method side, a reference of type
Foo
with a namea
is declared and it's initially assigned tonull
.public static void changeReference(Foo a)
As you call the method
changeReference
, the referencea
will be assigned to the object which is passed as an argument.changeReference(f);
Declaring a reference named
b
of typeFoo
and assign it to a new object of typeFoo
with an attribute"b"
.Foo b = new Foo("b");
a = b
is re-assigning the referencea
NOTf
to the object whose its attribute is"b"
.As you call
modifyReference(Foo c)
method, a referencec
is created and assigned to the object with attribute"f"
.c.setAttribute("c");
will change the attribute of the object that referencec
points to it, and it's same object that referencef
points to it.
I hope you understand now how passing objects as arguments works in Java :)
最新文章
- vue vue-cli安装
- Qt线程(4) 降低线程占用CPU
- php数组插入数据库这个功能该怎么实现
- Swift学习--常量.变量.数据类型的使用(一)
- 【转载】COM多线程原理与应用
- 持久化消息队列memcacheq的安装配置
- Oracle EBS-SQL (PO-11):检查采购订单退货数.sql
- while循环与i--
- 关于SELECT LAST_INSERT_ID()的使用规则
- kubernetes之监控Prometheus实战--prometheus介绍--获取监控(一)
- SDKmanager的位置
- js中浅拷贝和深拷贝以及深拷贝的实现
- Http协议中get和post的区别
- js替换字符中的斜杠反斜杠
- C# 实体/集合差异比较,比较两个实体或集合值是否一样,将实体2的值动态赋值给实体1(名称一样的属性进行赋值)
- 第三十二篇-NavigationView导航抽屉的使用
- Docker技术底层架构剖析
- plt实现动态画图
- 阿里云php-7.2.12 安装
- C#获取一个数组中的最大值、最小值、平均值
热门文章
- C++实现VPN工具之VPN错误代码大全
- iOS FMDB 不需要关闭
- Linux下安装Django
- JAVA中的Calendar得到当前时间的年份、月份、日期
- 【python】Head First Python(五)
- HDU 4793 Collision (解二元一次方程) -2013 ICPC长沙赛区现场赛
- JS调用自定义弹窗【bootstrap】
- <;context-param>;与<;init-param>;
- October 5th 2016 Week 41st Wednesday
- iOS 动态计算文本内容的高度