[英]Is it possible to call a subclasses' instance variable from its superclass in Java?
I've got a superclass Animal that is extended by Cat, Dog & Lion.我有一个由 Cat、Dog 和 Lion 扩展的超类 Animal。 These three all have a field
String sound
representing their sound.这三个都有一个字段
String sound
代表他们的声音。 The method playSound(int i, String s) plays the sound s, i amount of times.方法 playSound(int i, String s) 播放声音 s, i 次。 Could it be possible to have a general method in the Animal superclass that takes in the field of the subclass calling it?
是否有可能在 Animal 超类中有一个通用方法来接受调用它的子类的字段? Or do I have to make a separate, overriding method in each class that calls super with their own "sound" variable?
或者我是否必须在每个类中创建一个单独的覆盖方法,用自己的“声音”变量调用 super ?
The superclass can't access fields in the subclass.超类无法访问子类中的字段。 The usual approach here is to make an abstract getter:
这里通常的方法是创建一个抽象的 getter:
protected abstract Sound getSound();
public void playSound(int times) {
for(int i=0; i<times; i++) {
getSound().play();
}
}
The super has no access to the sub's fields, nor should it -- super classes should have no dependencies on their children -- but thanks to polymorphism, it doesn't need to. super 无法访问 sub 的字段,也不应该访问它——超类不应该依赖它们的子类——但是由于多态性,它不需要。 All you need to do is give super a
makeSound()
method, or something similar, and then have the sub's override the method, each playing its own sound.您需要做的就是给 super 一个
makeSound()
方法或类似的方法,然后让 sub 覆盖该方法,每个方法播放自己的声音。
re,关于,
Or do I have to make a separate, overriding method in each class that calls super with their own "sound" variable?
或者我是否必须在每个类中创建一个单独的覆盖方法,用自己的“声音”变量调用 super ?
I don't understand what you mean by "that calls super...".我不明白你所说的“那叫超级......”是什么意思。 You simply have the sub call its own sound within the
makeSound()
method override.您只需让 sub 在
makeSound()
方法覆盖中调用它自己的声音。
As far as I know, no, it's not possible.据我所知,不,这是不可能的。 You can try making comparisons in the superclass like
您可以尝试在超类中进行比较,例如
if (this intanaceof of Cat)
play cat sound
But that would kind of defeat the purpose of polymorphism.但这会违背多态的目的。 I don't see why you would want to do it this way though.
我不明白你为什么要这样做。 I'd do something like this:
我会做这样的事情:
abstract class Animal{
Sound [] sounds;
int soundI;
Animal(int soundI){
this.soundI = soundI
}
void playSound(){
sounds[i].play();
}
}
class Cat extends Animal{
Cat(){
super(5);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.