【问题标题】:Why are the changes of instance variables of Parent class reflected in Child class?为什么Parent类的实例变量的变化会反映在Child类中?
【发布时间】: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


    【解决方案1】:

    没有“父对象”和“子对象”。只有“一个对象”。

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

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

    【讨论】:

      【解决方案2】:

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

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

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

      我希望这有助于理解。

      【讨论】:

      • 我明白了,但他们俩的自行车不一样吗?这里计数给了我们不同的身份哈希码,这可能意味着它们是不同的对象
      • @0ne0rZer0 System.identityHashCode(Object x) 此方法需要一个对象作为参数。您将 int 变量传递给它,即 int count。尝试使用包装类Integer。这可能与将 int 自动装箱为 Integer 有关。
      • 我用字符串的实例变量尝试过,你能告诉我如何使用包装类来做同样的事情吗?
      • @0ne0rZer0 对应于每个原始数据类型,存在一个包装类。就像代替int 一样,我说的是Integer。没有任何需要使用String,您也可以通过Integer 实现同样的效果。您可以阅读有关包装类的更多信息here
      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2020-06-08
        • 2021-09-25
        • 1970-01-01
        • 2016-05-27
        • 1970-01-01
        • 1970-01-01
        • 2020-09-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多