2017-07-31 107 views
1

我想改变一个对象的引用,我写了下面的代码。Java - 如何使用方法更改引用?

public class Test { 
    public static void main(String[] args) { 
     Foo foo1 = new Foo(); 
     Foo foo2 = new Foo(); 
     System.out.println("the reference of foo1 is " + foo1); 
     System.out.println("the reference of foo2 is " + foo2); 
     System.out.println(); 
     change(foo1, foo2); 
     System.out.println("the reference of foo1 is " + foo1); 
     System.out.println("the reference of foo2 is " + foo2); 
    } 

    public static void change(Foo foo1, Foo foo2) { 
     System.out.println("the reference of foo1 is " + foo1); 
     System.out.println("the reference of foo2 is " + foo2); 
     System.out.println(); 
     foo1 = foo2; 
     System.out.println("the reference of foo1 is " + foo1); 
     System.out.println("the reference of foo2 is " + foo2); 
     System.out.println(); 
    } 
} 

class Foo { 
    public Foo() { 
     // do nothing 
    } 
} 

我得到了以下输出。

the reference of foo1 is [email protected] 
the reference of foo2 is [email protected] 

the reference of foo1 is [email protected] 
the reference of foo2 is [email protected] 

the reference of foo1 is [email protected] 
the reference of foo2 is [email protected] 

the reference of foo1 is [email protected] 
the reference of foo2 is [email protected] 

change的方法从[email protected]改变foo1提及[email protected]change方法,但foo1参考在main方法并没有改变。为什么?

+0

我不知道你所说的“改变对象的引用”的意思,但我强烈怀疑,你的问题将在[在此页面](https://stackoverflow.com/q/40480)上得到解答 - 这样我就很想将它作为一个副本来关闭它。 –

+0

@Reimeus标记的副本不正确。问题是关于传递引用。 在Java中,引用是作为COPIES传递到方法中的。任何重新分配只保留在该范围的本地。 – Kon

回答

1

在Java中,方法的所有参数都是按值传递的。请注意,非基元类型的变量(它们是对象的引用)也是按值传递的:在这种情况下,引用是按值传递的。

所以你的情况,你在你的函数做的修改不使用改变对象的主要

相关问题