【问题标题】:Why is the child class object invoking the parent class field variable in Java?为什么子类对象在Java中调用父类字段变量?
【发布时间】:2020-10-22 17:00:28
【问题描述】:

这是我的代码,非常简单和演示:

JVM入口:

class Demo {
    public static void main(String[] args) {
        new Dog().start();
    }
}

父类:

public class Animal {
    int num = 100;
    public void call() {
        System.out.println(this.num);
    }

}

儿童班:

 public class Dog extends Animal{
        int num = 10000;
        public void start() {
            this.call();
        }
    }

控制台输出:100

为什么是 100,而不是 10000?这个怎么理解?

【问题讨论】:

    标签: java inheritance polymorphism field


    【解决方案1】:

    您的实例有两个字段:Animal::numDog::numAnimal::call() 只知道 Animal::num,也就是 100。

    在子类中声明与超类中的字段同名的字段通常没有帮助。字段不受覆盖;隐藏名称只会导致混乱。


    假设您没有在Dog 中声明一个新的num 字段,而是将现有的num 字段设置为一个新值。

    class Dog extends Animal {
        public Dog() {
            num = 10000;
        }
        public void start() {
            this.call();
        }
    }
    

    现在如果你运行new Dog().start(),你会发现打印了10000。该实例只有一个num 字段,在Animal 中声明,在Dog 中设置为10000。

    【讨论】:

      猜你喜欢
      • 2021-11-16
      • 2013-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多