gpt4 book ai didi

java - 访问父类(super class)中方法的变量

转载 作者:搜寻专家 更新时间:2023-11-01 03:51:34 24 4
gpt4 key购买 nike

我有一个包含 Animal 类以及 Dog 和 Cat 子类的基本代码。我有一个说话的方法。 speak 方法接收一个字符串,并以猫狗“语言”返回一个字符串。如果字符的 ascii 码是偶数,则返回“uff”,否则返回“vau”。当我重写该方法时,我想从 Dog 类设置 oddSound 和 evenSound,但是我找不到合适的方法来执行此操作。
此代码来自 Animal 类:

public String speak(String what){
String speakableString = new String();
String oddSound = new String();
String evenSound = new String();

for (int i = 0; i < what.length(); i++) {
if((((int) what.charAt(i)) & 1) == 1){
speakableString.concat(oddSound);
}else if ((((int) what.charAt(i)) & 1) == 0){
speakableString.concat(evenSound);
}
}

speakableString = speakableString.substring(0, speakableString.length()-1);
return speakableString;
}

此代码来自 Dog 类:

public String speak(String what){
//set oddSound = "vau"
//set evenSound = "uff"
return super.speak(what);
}

最佳答案

Animal类中,有两个 protected 字段,

protected String oddSound;
protected String evenSound;

然后,在DogCat 类中,您可以设置这些字段:

oddSound = "woof";
evenSound = "woofwoof"

然后,在speak() 方法中,您可以简单地使用this.oddSoundthis.evenSound

关于java - 访问父类(super class)中方法的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26329654/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com