[英]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::num
和Dog::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.