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;
}
对比.代码 B:
Foo myFoo;
createFoo(myFoo);
public void createFoo(Foo foo)
{
Foo f = new Foo();
foo = f;
}
这两段代码有什么区别吗?
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");
}
}
我将分步解释:
声明一个名为
f
的类型为Foo
的引用,并将其分配给一个类型为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");
在方法方面,声明了一个名为 a
的 Foo
类型的引用,并且它最初被分配给 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);
声明一个名为 b
的类型为 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
而不是 f
重新分配给其属性为 的对象"b"
.
a = b
is re-assigning the reference a
NOT f
to the object whose its attribute is "b"
.
当您调用 modifyReference(Foo c)
方法时,会创建一个引用 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
指向它的对象的属性,并且引用 c
的对象是同一个对象code>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屋!