引用对象如何在java中工作

时间:2014-04-12 11:16:11

标签: java object

任何人都可以让我明白吗?参考对象如何在java中从下面的代码中工作我有对象r1和引用对象r2Rectangle r1 = new Rectangle(); Rectangle r2 = r1; 当我同时打印r1r2时,输出就像这样Rectangle@17f7bec4(两者输出相同)。好的,我明白这是内存地址吧?如果我打印下面的代码

  r1.length = 50;
  r2.length = 20;

  System.out.println("Value of R1's Length : " + r1.length);
  System.out.println("Value of R2's Length : " + r2.length);

上述代码的输出是:

R1的长度值:20

R2的长度值:20

我无法理解这个输出为什么两者都有20值? 如果这是因为引用内存,那么当我使用下面的代码

  Rectangle r1 = new Rectangle();
  Rectangle r2 = r1;
  r2 = null;

 System.out.println("R1 : " + r1);
 System.out.println("R2 : " + r2);

两个对象的输出:

R1:Rectangle@17f7bec4

R2:null

为什么r1没有null值?这是让我感到困惑 下面是运行代码..

class Rectangle {
  double length;
  double breadth;
}

class RectangleDemo {
  public static void main(String args[]) {

  Rectangle r1 = new Rectangle();
  Rectangle r2 = r1;

r1.length = 50;
r2.length = 20;


  System.out.println("R1 : " + r1);
  System.out.println("Value of R1's Length : " + r1.length);
  System.out.println("Value of R2's Length : " + r2.length);
r2 = null;
  System.out.println("R2 : " + r2);

  }
}

3 个答案:

答案 0 :(得分:2)

r1r2是对象的引用。在第一种情况下,它们都指向同一个对象,在第二种情况下r2指向null。在您的代码中,只有一个非空对象和两个引用


对您的代码的评论

Rectangle r1 = new Rectangle();    //object creation, make r1 point to created object
Rectangle r2 = r1;                 //r2 now points to the same object, that was created a line above

r1.length = 50;    //change lenght of object r1 points to
r2.length = 20;    //change lenght of object r2 points to (the same object as r1 points to)

r2 = null; //make r2 point to null

答案 1 :(得分:2)

您的对象是在堆中创建的,它有一个地址。

Rectangle r1 = new Rectangle();
// r1 is pointing to that address
Rectangle r2 = r1;
// now r2 is pointing to the same address (same object) with r1
r2 = null;
// now r2 is null, but the object is still in the heap.
// r2 doesn't point to that object anymore.

enter image description here

答案 2 :(得分:1)

任何语言的工作方式都相同。

Rectangle r1 = new Rectangle(); //r1 refers to this new Rectangle
Rectangle r2 = r1; //now r2 refers to the same Rectangle r1 refers to
r2 = null; //now is referring to null

您可以将r1设置为null,它将具有相同的行为。

如果将r2更改为final,则不允许更改它。

Rectangle r1 = new Rectangle();
final Rectangle r2 = r1; //now r2 will be forever referring to the Rectangle above even if you change r1 to null

如果你将r1更改为null,请检查它r2仍将指向Rectangle ...当你告诉r2 = r1 ... r2没有指向r1时,r2实际上是指向Rectangle本身!

Rectangle r1 = new Rectangle(2, 2);
final Rectangle r2 = r1; // now r2 will be forever referring to the
             // Rectangle above even if you change r1 to
             // null
r1 = null;
System.out.print(r2.getWidth());

输出宽度仍然是2且没有空错误。