Java Class reference


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(("不返回空错误。 它应该是空的,对吧?

解释在代码中:

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());
}
}

相关内容

最新更新