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

huangapple go评论82阅读模式
英文:

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

问题

这是我的代码,非常简单且具有示范性:

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?如何理解这个问题?

英文:

This is my code, pretty simple and demonstrative:

JVM entrance:

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

Why it's 100, not 10000? How to comprehend this?

答案1

得分: 2

你的实例有两个字段: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。

英文:

Your instance has two fields: Animal::num and Dog::num. Animal::call() only knows about Animal::num, which is 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.

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. The instance has only one num field, declared in Animal, and set to 10000 inside Dog.

huangapple
  • 本文由 发表于 2020年10月23日 01:00:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/64487053.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定