无法理解问题"call By Reference"

  • 本文关键字:call Reference By 问题 java
  • 更新时间 :
  • 英文 :


在Java中,对象引用用于按引用调用,变量用于按值调用。

下面是一个示例:

class Foo{
    int x;
    int y;
}  

public class CallByRef {
    public static void main(String[] args) {            
        Foo foo = new Foo();
        foo.x=5;
        foo.y=10;
        System.out.println(foo.x+", "+foo.y);
        getFoo(foo);
        System.out.println(foo.x+", "+foo.y);
    }    
    static void getFoo(Foo f){
        f.x=2;
        f=new Foo();
        f.x=10;
    }
}

输出:

5, 10    
2, 10

为什么会这样?

x应该是 10,因为我用 f.x=10 修改了它的值

f=new Foo()将在堆中创建新对象而不指向 prevoise 引用是否正确?

> 在方法getFoo中,变量f是一个局部变量。

当你从main调用getFoo(foo)时,这个变量确实指的是foo

但是一旦你设置了f = new Foo(),它指的是一个不同的对象。

因此,在这一点上,更改f.x不会影响foo.x

以下是您的案例中发生的基本描述作为示例

// Creating a new object of Foo 
// The variable foo now stores a VALUE!!! to the memory where the 
// Instance of foo is stored
Foo foo = new Foo(); 
// accesing the instance of Foo over the value to the reference in the memory 
// and set x to 5
foo.x = 5
// accesing the instance of Foo over the value to the reference in the memory 
// and set y to 5
foo.x = 10
// Print out x and y of the instance of Foo where the value of the reference to memeory points to
System.out.println(foo.x+", "+foo.y);

现在到让Foo做什么

// The instance f of Foo holds the value to the reference in the memory
// Lets call it 1234567 as example
static void getFoo(Foo f){
    // The object in the memory 1234567 is going to have x changed 
    f.x=2;
    // The VALUE of the reference is changed, lets say it now refers to the memory 123456789 where a new instance of Foo is stored now
    f=new Foo();
    // The object in the memory 123456789 is going to have x changed 
    f.x=10;
}

让我们回到您上次的输出以及它现在打印的内容

//  So in your getFoo() Call your first action was to change the value of x 
//  on the object with the value to the reference which you gave as a parameter
// hence it prints 2
// The new instance of the Object Foo that is stored somewhere else in the memory should be garbage collected soon, since no variable actually holds the VALUE to the reference anymore
System.out.println(foo.x+", "+foo.y);

最需要理解的部分是,变量或参数中对对象的引用实际上作为值存储到内存中。因此,您的 getFoo() 方法只是更改对对象实例的引用值,但永远无法更改引用本身

我认为第一种情况对您来说很清楚,即值5,10

之后getFoo()调用方法并传递相同的对象foo作为参数传递。在该方法getFoo(),同一对象(foo)的实例变量值更改为 2。但在那之后,它使用new键创建新对象并分配另一个值。即。

foo => x=2(new value) and y=10(not changed, so it takes old value)
f => x=10 and y=0(not assigned)

你正在打印foo的价值观。

因此结果2,10

最新更新