Java通过引用传递 [英] Java pass by reference
问题描述
这两个代码有什么区别:
What is the difference between this 2 codes:
代码A:
Foo myFoo;
myFoo = createfoo();
其中
public Foo createFoo()
{
Foo foo = new Foo();
return foo;
}
Vs。代码B:
Foo myFoo;
createFoo(myFoo);
public void createFoo(Foo foo)
{
Foo f = new Foo();
foo = f;
}
这2个代码之间是否有任何差异?
Are there any differences between these 2 pieces of codes?
推荐答案
Java总是按值而不是通过引用传递参数。
Java always passes arguments by value NOT by reference.
让我通过示例解释一下:
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");
}
}
我将分步说明:
-
声明类型为
Foo的名为
并将其分配给类型为f
的引用Foo
的新对象,其属性为f
。
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");
从方法方面,类型为 Foo
的引用声明名称 a
,并且它最初被分配给 null
。
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)
当你调用方法 changeReference
,引用 a
将被分配给作为参数传递的对象。
As you call the method changeReference
, the reference a
will be assigned to the object which is passed as an argument.
changeReference(f);
声明类型为<$ c的名为 b
的引用$ c> Foo 并将其分配给类型为 Foo
的新对象,其属性为b
。
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");
a = b
正在重新分配参考 a
NOT f
到属性为b的对象
。
a = b
is re-assigning the reference a
NOT f
to the object whose its attribute is "b"
.
当您调用 modifyReference(Foo c)
方法时,a引用 c
已创建并分配给属性为f
的对象。
As you call modifyReference(Foo c)
method, a reference c
is created and assigned to the object with attribute "f"
.
c.setAttribute(c);
将更改引用 c
点的对象的属性对它来说,引用 f
指向它是同一个对象。
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.
我希望您现在了解如何将对象作为参数传递在Java中:)
I hope you understand now how passing objects as arguments works in Java :)
这篇关于Java通过引用传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!