为什么Parentclass实例变量的变化会反映到Childclass?

Why are the changes of instance variables of Parent class reflected in Child class?

如果我更改 parent class 的实例变量,即使它们具有不同的 identityHashCode,更改也会反映在 Child class 中。为什么会这样?

我已经尝试创建 child 自己的实例变量,但由于引用类型调用,这些实例变量不会反映更改。此外,我首先调用了打印实例变量的 child 方法,然后调用了 parent 的方法,该方法进行了一些更改,然后打印。这证明更改是动态完成的,而不是在编译时完成的。我已经尝试使用这两种构造函数,它们对我的问题没有任何重大影响。

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

}

预期结果的更改仅限于 parent class。 实际结果显示变化反映到 Child object 也。

没有 "parent object" 和 "child object"。只有 "an object"。

A class(或多或少)只是创建对象的蓝图。通过继承,一些蓝图写在父类中,一些蓝图写在子类中。

在你的例子中,你的对象是一本书。这本书恰好具有从图书馆继承的一些特征,但它仍然是一本书。没有书和图书馆作为不同的对象。 (这是一个非常奇怪的继承模型:图书馆与书籍几乎没有共同之处)

我认为您的主要困惑在于对 System.identityHashCode 的理解,正如评论所说:

 Returns the same hash code for the given object as
 would be returned by the default method hashCode(),
 whether or not the given object's class overrides
 hashCode(). 

如果您将参数从 count 更改为 this,它们将 return 相同的值。如果您想将它们分开,您可以在 Book class 中定义计数以覆盖父级。

我会尝试用一个奇怪的例子来更简单地解释它,但这可能有助于理解这个概念。

比如说父亲给儿子买了一辆自行车,儿子就可以说这是他的自行车(因为他是从父亲那里继承来的),他想骑就骑。

现在假设自行车里还剩 1 升汽油,父亲把油箱加满了,那么当他儿子下次看到自行车时,他也会加满油。

希望对理解有所帮助。