这个Java属性继承的例子有什么问题? [英] What's wrong with this example of Java property inheritance?
问题描述
public class InheritanceExample {
static public void main(String[] args){
Cat c = new Cat();
System.out.println(c.speak());
Dog d = new Dog();
System.out.println(d.speak());
}
}
Animal.java
Animal.java
public class Animal {
protected String sound;
public String speak(){
return sound;
}
}
Cat.java
Cat.java
public class Cat extends Animal {
protected String sound = "meow";
}
Dog.java
Dog.java
public class Dog extends Animal {
protected String sound = "woof";
}
输出:
Output:
null
null
我的动物不会说话。太伤心了。
My animals cannot speak. So sad.
推荐答案
字段不是多态的。你已经声明了三个完全不同的字段...... Cat
和 Dog
shadow 或隐藏 Animal
中的那个。
Fields aren't polymorphic. You've declared three entirely distinct fields... the ones in Cat
and Dog
shadow or hide the one in Animal
.
最简单(但不一定是最好的)获取当前代码的方法是从 Cat
和 Dog $中删除
声音
c $ c>,并在 Cat $ c $的构造函数中设置继承的
声音
字段的值c>和狗
。
The simplest (but not necessarily best) way of getting your current code is to remove sound
from Cat
and Dog
, and set the value of the inherited sound
field in the constructor for Cat
and Dog
.
更好的方法是使 Animal
abstract,并给它一个受保护的构造函数,它接受声音... Cat
和的构造函数Dog
然后将分别调用 super(meow)
和 super(woof)
:
A better approach would be to make Animal
abstract, and give it a protected constructor which takes the sound... the constructors of Cat
and Dog
would then call super("meow")
and super("woof")
respectively:
public abstract class Animal {
private final String sound;
protected Animal(String sound) {
this.sound = sound;
}
public String speak(){
return sound;
}
}
public class Cat extends Animal {
public Cat() {
super("meow");
}
}
public class Dog extends Animal {
public Dog() {
super("woof");
}
}
这篇关于这个Java属性继承的例子有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!