【问题标题】:Java Class referenceJava 类参考
【发布时间】:2020-01-29 01:50:06
【问题描述】:
Animal remove = te.head;
te.head.size = 8;
te.head = null;



System.out.print(remove.getSize()); //gets 8, not null

类动物

class Animal{
    int size;

    public Animal(int data) {
       this.size = data; 
    }

    public int getSize() {
       return this.size;
    }
}

我很难理解变量“remove”引用了“te.head”,并且在使用方法“getSize()”时返回 8,而不是 null。

我是java初学者,请解释为什么“remove.geSize()”不返回null错误。应该是null吧?

【问题讨论】:

  • 能添加Animal类的代码吗?除非代码在那里,否则无法知道 remove() 是什么。
  • @Scratte 我添加了
  • remove 引用了 te.head,原来对 Animal 的引用被取消了。但是您已经创建了引用的副本。那就是System.out.print(te.head); 将输出null
  • @ElliottFrisch 但实际上他们使用的是相同的地址,对吧?这就是为什么当变量更改为 5 或任何数字时,“删除”也发生了变化。所以 remove 也应该为 null - 这是我的观点
  • 非常感谢!我得到了它! @ElliottFrisch

标签: java class reference


【解决方案1】:

解释在代码里面:

public class StackOverflowTest {
    public static void main(String[] args) {
    // creating one Animal and setting teHead to point to it
    Animal teHead = new Animal(9);  

    // setting a new reference to the same Animal
    // now there are two references pointing to the same Object
    Animal remove = teHead;         

    // Changing the content of the Animal
    teHead.size = 8;
    System.out.println(remove.getSize());

    // teHead is now not pointing anywhere. But remove is still pointing to Animal
    teHead = null;   
    System.out.println(remove.getSize());
    // Using teHead now will give a NullPointerException
//    System.out.print(teHead.getSize());

    remove = null;   // Now nothing is pointing to Animal

    // Using remove now will give a NullPointerException
//    System.out.print(remove.getSize());
  }
}

【讨论】:

    猜你喜欢
    • 2010-11-02
    • 2016-08-16
    • 2012-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多