【发布时间】:2019-11-27 20:30:33
【问题描述】:
如果我更改父类的实例变量,则更改会反映在子类中,即使它们具有不同的 identityHashCodes。为什么会这样?
我尝试过创建孩子自己的实例变量,但由于引用类型调用,这些变量不会反映更改。另外,我首先调用了打印实例变量的子方法,然后调用了父方法,它进行了一些更改然后打印。这证明更改是动态完成的,而不是在编译时完成的。我已经尝试使用这两种构造函数,它们对我的问题没有任何重大影响。
class Library{
int count = 500;
int years = 70;
Library(){
System.out.println(" Constructor library ");
}
Library(int count,int years){
this.count = count;
this.years = years;
System.out.println(" Constructor library ");
}
void libraryInfo(){
count++;
System.out.println(System.identityHashCode(count));
System.out.println(" Years " + years);
System.out.println(" Count " + count);
}
}
class Book extends Library{
//int count = 500;
//int years = 70;
Book(){
super(700,80);
// super();
}
void libraryInfo(){
super.libraryInfo();
System.out.println(System.identityHashCode(count));
System.out.println(" Years " + years);
System.out.println(" Count " + count);
//super.libraryInfo();
}
public static void main(String args[]){
Book b = new Book();
b.libraryInfo();
}
}
预期结果是更改仅限于父类。 实际结果显示更改也反映到 Child 对象。
【问题讨论】:
标签: java inheritance instance-variables