简体   繁体   English

为什么子类对象在Java中调用父类字段变量?

[英]Why is the child class object invoking the parent class field variable in Java?

This is my code, pretty simple and demonstrative:这是我的代码,非常简单且具有示范性:

JVM entrance: JVM入口:

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

Parent class:父类:

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

}

Child class:儿童班:

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

Console output: 100控制台输出:100

Why it's 100, not 10000?为什么是 100,而不是 10000? How to comprehend this?如何理解这一点?

Your instance has two fields: Animal::num and Dog::num .您的实例有两个字段: Animal::numDog::num Animal::call() only knows about Animal::num , which is 100. Animal::call()只知道Animal::num ,它是 100。

It is not usually helpful to declare a field in a subclass with the same name as a field in the superclass.在子类中声明与超类中的字段同名的字段通常没有帮助。 Fields are not subject to overriding;字段不受覆盖; and shadowing a name only leads to confusion.隐藏名称只会导致混淆。


Suppose that instead of declaring a new num field in Dog , you set the existing num field to a new value.假设不是在Dog中声明新的num字段,而是将现有的num字段设置为新值。

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

Now if you run new Dog().start() , you will find that 10000 is printed.现在,如果您运行new Dog().start() ,您会发现打印了 10000。 The instance has only one num field, declared in Animal , and set to 10000 inside Dog .该实例只有一个num字段,在Animal声明,在Dog设置为 10000。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Java中将父类分配给子类变量 - Assign parent class to child class variable in Java 为什么父类对子类对象的引用不能访问子类变量? - Why parent class ref to child class object cannot access child class variable? 在Java中,为什么在父类和子类中声明的变量在子类的实例中是不可见的? - In Java, why would a variable declared in both a parent and child class be invisible in an instance of the child class? 查找字段在 Java 中属于哪个类,父类还是子类? - Find field is of which class, parent or child in Java? 有没有办法在java中用父对象实例化子类? - Is there a way to instantiate a child class with parent object in java? Java - 比较父类对象上的子属性 - Java - Compare child property on Parent Class Object 为什么引用子类对象的父类类型引用变量无法访问子类的方法 - Why parent class type reference variable having reference to child class object can't access child class's Methods Java中的方法重写-将子类对象分配给父类变量 - Method overriding in Java- assigning child class object to parent class variable 尽管子类中也有相同的方法,如何阻止子类对象从父类调用方法 - How to stop child class object invoking method from parent class despite same method also being in child class 当变量是抽象父类时,Java将分派给子类 - Java dispatch to child class when variable is of abstract parent class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM