为什么父类的实例变量的变化反映在子类中



如果我更改父类的实例变量,则更改将反映在子类中,即使它们具有不同的身份哈希码。为什么会这样?

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

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 对象。

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

假设父亲为儿子买了一辆自行车,那么他的儿子可以说这是他的自行车(因为他从父亲那里继承了它(,他可以随时骑它。

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

我希望这有助于理解。

没有"父对象"和"子对象"。只有"一个对象"。

类(或多或少(只是创建对象的蓝图。 使用继承时,一些蓝图写入父级,一些蓝图写入子级。

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

我认为你的主要困惑在于对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 更改为此值,它们将返回相同的值。如果您想将 Book 类分开,可以在 Book 类中定义计数以覆盖父级。

最新更新