Vin*_*C M 9 java terminology parameter-passing pass-by-reference pass-by-value
我有以下代码,它有
一个可变的Person类,String和一个修改String和Person实例的方法
class Person{
int a = 8;
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
@Override
public String toString() {
return "Person [a=" + a + "]";
}
}
Run Code Online (Sandbox Code Playgroud)
-
public class TestMutable {
public static void main(String[] args)
{
Person p = new Person();
p.setA(34);
String s = "bar";
modifyObject(s, p); //Call to modify objects
System.out.println(s);
System.out.println(p);
}
private static void modifyObject(String str, Person p)
{
str = "foo";
p.setA(45);
}
}
Run Code Online (Sandbox Code Playgroud)
输出符合预期.它打印
bar
Person [a=45]
Run Code Online (Sandbox Code Playgroud)
现在,我的问题是
在你说str ="foo"的地方发生了什么?
最初让我们假设s ='bar',数据驻留在0x100内存中
现在将string的引用传递给另一个方法,另一个方法尝试使用s ="foo"将内存位置(0x100)的内容更改为'foo'.这是发生了什么,或者'foo'是在不同的内存位置创建的?
java是否按值传递引用?
Eng*_*uad 27
Java总是按值而不是通过引用传递参数.
让我通过一个例子解释一下:
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 change 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");
}
}
Run Code Online (Sandbox Code Playgroud)
我将逐步解释这个:
1-声明名为ftype 的引用,Foo并将其分配给Foo具有属性的新对象类型"f".
Foo f = new Foo("f");
Run Code Online (Sandbox Code Playgroud)

2-从方法方面,声明Foo具有名称的类型引用,a并将其初始分配给null.
public static void changeReference(Foo a)
Run Code Online (Sandbox Code Playgroud)

3-在调用方法时changeReference,引用a将分配给作为参数传递的对象.
changeReference(f);
Run Code Online (Sandbox Code Playgroud)

4-声明一个名为btype 的引用,Foo并将其分配给Foo具有属性的新对象类型"b".
Foo b = new Foo("b");
Run Code Online (Sandbox Code Playgroud)

5- a = b是将引用aNOT 重新分配给f其属性为的对象"b".

6-在调用modifyReference(Foo c)方法时,将c创建一个引用并将其分配给具有属性的对象"f".

7- c.setAttribute("c");将更改引用c指向它的对象的属性,并且它是引用f指向它的同一对象.

我希望你现在明白如何将对象作为参数传递在Java中:)
| 归档时间: |
|
| 查看次数: |
3048 次 |
| 最近记录: |