繁体   English   中英

是否可以从 Java 中的超类调用子类的实例变量?

[英]Is it possible to call a subclasses' instance variable from its superclass in Java?

我有一个由 Cat、Dog 和 Lion 扩展的超类 Animal。 这三个都有一个字段String sound代表他们的声音。 方法 playSound(int i, String s) 播放声音 s, i 次。 是否有可能在 Animal 超类中有一个通用方法来接受调用它的子类的字段? 或者我是否必须在每个类中创建一个单独的覆盖方法,用自己的“声音”变量调用 super ?

超类无法访问子类中的字段。 这里通常的方法是创建一个抽象的 getter:

protected abstract Sound getSound();

public void playSound(int times) {
    for(int i=0; i<times; i++) {
        getSound().play();
    }
}

super 无法访问 sub 的字段,也不应该访问它——超类不应该依赖它们的子类——但是由于多态性,它不需要。 您需要做的就是给 super 一个makeSound()方法或类似的方法,然后让 sub 覆盖该方法,每个方法播放自己的声音。

关于,

或者我是否必须在每个类中创建一个单独的覆盖方法,用自己的“声音”变量调用 super ?

我不明白你所说的“那叫超级......”是什么意思。 您只需让 sub 在makeSound()方法覆盖中调用它自己的声音。

据我所知,不,这是不可能的。 您可以尝试在超类中进行比较,例如

if (this intanaceof of Cat)
play cat sound

但这会违背多态的目的。 我不明白你为什么要这样做。 我会做这样的事情:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM