Java学习随笔1:Java是值传递还是引用传递?
2015-10-18 10:01
531 查看
Java always passes arguments by value NOT by reference.
Let me explain this through an example:
I will explain this in steps:
Declaring a reference named
![](http://i.stack.imgur.com/arXpP.png)
From the method side, a reference of type
![](http://i.stack.imgur.com/k2LBD.png)
As you call the method
![](http://i.stack.imgur.com/1Ez74.png)
Declaring a reference named
![](http://i.stack.imgur.com/Krx4N.png)
![](http://i.stack.imgur.com/rCluu.png)
As you call
![](http://i.stack.imgur.com/PRZPg.png)
![](http://i.stack.imgur.com/H9Qsf.png)
I hope you understand now how passing objects as arguments works in Java :)
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
fof type
Fooand assign it to a new object of type
Foowith an attribute
"f".
Foo f = new Foo("f");
![](http://i.stack.imgur.com/arXpP.png)
From the method side, a reference of type
Foowith a name
ais declared and it's initially assigned to
null.
public static void changeReference(Foo a)
![](http://i.stack.imgur.com/k2LBD.png)
As you call the method
changeReference, the reference
awill be assigned to the object which is passed as an argument.
changeReference(f);
![](http://i.stack.imgur.com/1Ez74.png)
Declaring a reference named
bof type
Fooand assign it to a new object of type
Foowith an attribute
"b".
Foo b = new Foo("b");
![](http://i.stack.imgur.com/Krx4N.png)
a = bis re-assigning the reference
aNOT
fto the object whose its attribute is
"b".
![](http://i.stack.imgur.com/rCluu.png)
As you call
modifyReference(Foo c)method, a reference
cis created and assigned to the object with attribute
"f".
![](http://i.stack.imgur.com/PRZPg.png)
c.setAttribute("c");will change the attribute of the object that reference
cpoints to it, and it's same object that reference
fpoints to it.
![](http://i.stack.imgur.com/H9Qsf.png)
I hope you understand now how passing objects as arguments works in Java :)
相关文章推荐
- I/O failure during classpath scanning in spring MVC
- Javassist介绍
- Javassist介绍
- Javassist介绍
- ztree异步加载简单示例(struts2)
- 启动项目出现:java.lang.NoClassDefFoundError: org/springframework/asm/ClassVisitor
- Spring4.0 学习(五)web.xml中ContextLoaderListeners的运行过程
- Java 八大排序之——归并排序
- java--通过sax方式解析xml文件的简单实例
- Java 八大排序之——快速排序
- Java 八大排序之——堆排序
- Spring的特点
- Java 实现栈
- Spring常用注解---IoC
- Java的静态方法、静态属性、静态代码块
- java定时任务
- java中的权限
- spring aop 权限管理
- Java基础知识强化100:JVM(Java虚拟机)内存体系 与 对象访问
- Java 类反射机制分析