覆盖父类

时间:2014-04-11 17:21:43

标签: java

我有 Pet 超级类,然后有一个 Dog 子类,我的超类中的一个特定方法是getSpecies()。在我的子类中,我希望能够返回super.getSpecies(),但也会在该方法中返回另一个变量(在这种情况下,气味)。

超级课程

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;
    }
}

2 个答案:

答案 0 :(得分:3)

您无法在单个函数中返回两个值。你需要做的是使用你的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;
    }

}

然后让我们说你想要物种和气味,你必须检查宠物是否实际上是一只狗,如果它是,你可以安全地把它作为狗,并使用狗类的具体方法。 / p>

if ( pet instanceof Dog ) {
    String species = pet.getSpecies();
    String smell = (Dog)pet.getSmell();
}

答案 1 :(得分:-2)

首先要做的事情是:在调用super.getSpecies()时,您应该在某处保存或移交它的返回值。然后你可以考虑将这个返回字符串连接成你的第二个返回值(high),如下所示:

public String getSpecies(){
   return "high " + super.getSpecies();
}

可是:

  • high dog的回归对IMO没有多大意义。
  • 一个getter只能返回一个值,即它的名字来源。

除了传递将结果作为参数的对象外,没有其它方法可以返回多个值。但是,这个解决方案远非一个简单的吸气剂。

您应该考虑(如下面的评论中指出的Pilibobby)在您的案例中使用两个不同的getter getSpecies()getSmell(),并将结果合并到您调用的地方来自。