我有我的 Pet 父类(super class),它还有一个 Dog 子类,我的父类(super class)中的一个特定方法是 getSpecies()。在我的子类中,我希望能够返回 super.getSpecies()
,而且还在该方法内返回另一个变量(在本例中为气味)。
super 类:
public class Pet {
protected int lifeSpan;
protected String species, name, interaction;
public Pet(){
}
public Pet(int lifeSpan, String species, String name){
this.lifeSpan = lifeSpan;
this.species = species;
this.name = name;
}
public final float costs(float cost){
return cost;
}
public void setSpecies(String species){
this.species = species;
}
public String getSpecies(){
return this.species;
}
}
子类“狗”:
public class Dog extends Pet{
protected String smell;
private String species;
public Dog(String smell){
super(15, "Dog", "Rex");
this.smell = smell;
}
public Dog(){
}
public void setSmell(String smell){
this.smell = smell;
}
public String getSpecies(){
super.getSpecies();
smell = "high"; //Meant to deliberately set it to "High". How am I to return this?
}
public String getSmell(){
return this.smell;
}
}
最佳答案
不能在单个函数中返回两个值。你所要做的就是使用你的 getter 来替代气味成员变量。
public class Dog extends Pet{
protected String smell;
private String species;
public Dog(String smell){
super(15, "Dog", "Rex");
this.smell = smell;
}
public Dog(){
}
public void setSmell(String smell){
this.smell = smell;
}
public String getSpecies(){
super.getSpecies();
}
public String getSmell(){
return this.smell;
}
}
然后假设您想要物种和气味,您必须检查宠物是否实际上是狗,如果是,您可以安全地将其转换为狗并使用 Dog 类的特定方法。
if ( pet instanceof Dog ) {
String species = pet.getSpecies();
String smell = (Dog)pet.getSmell();
}
关于java - 重写父类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23018854/