Java继承-子类方法重写

时间:2018-07-02 19:24:20

标签: java

我在Java的继承任务中苦苦挣扎

为我提供了Animal.java类。我的作业是创建一个名为Lion.java的子类。我在整个任务中苦苦挣扎的任务之一是根据狮子的重量输出它的Lion类型。这是Animal.java的代码

public class Animal {
    private int numTeeth = 0;
    private boolean spots = false;
    private int weight = 0;

    public Animal(int numTeeth, boolean spots, int weight){
        this.setNumTeeth(numTeeth);
        this.setSpots(spots);
        this.setWeight(weight);
    }

    public int getNumTeeth(){
        return numTeeth;
    }

    public void setNumTeeth(int numTeeth) {
        this.numTeeth = numTeeth;
    }

    public boolean getSpots() {
        return spots;
    }

    public void setSpots(boolean spots) {
        this.spots = spots;
    }

    public int getWeight() {
        return weight;
    }

    public void setWeight(int weight) {
        this.weight = weight;
    }

    public static void main(String[] args){
        Lion lion = new Lion(30, false, 80);
        System.out.println(lion);
    }


}

这是到目前为止我对Lion.java类的代码:

public class Lion extends Animal {
    String type = "";

    public Lion(int numTeeth, boolean spots, int weight) {
        super(numTeeth, spots, weight);
    }
    public String type(int weight){
        super.setWeight(weight);
        if(weight <= 80){
            type = "Cub"; 
        }
        else if(weight <= 120){
            type = "Female";
        }
        else{
            type = "Male";
        }
        return type;
    }
    @Override
    public String toString() { 
        String output = "Number of Teeth: " + getNumTeeth(); 
        output += "\nDoes it have spots?: " + getSpots();
        output += "\nHow much does it weigh: " + getWeight();
        output += "\nType of Lion: " + type;
        return output;

问题是输出未根据上述if语句返回类型。这可能是一个非常简单的解决方案,但我似乎无法弄清楚。

2 个答案:

答案 0 :(得分:0)

在toString方法中,而不是用type()方法进行类型替换。

@Override
public String toString() { 
      String output = "Number of Teeth: " + getNumTeeth(); 
      output += "\nDoes it have spots?: " + getSpots();
      output += "\nHow much does it weigh: " + getWeight();
      output += "\nType of Lion: " + type(getWeight());
      return output;

答案 1 :(得分:0)

看看您的Lion构造函数

public Lion(int numTeeth, boolean spots, int weight) {
    super(numTeeth, spots, weight);
}

这对类型(您的公开type方法)没有任何作用。

要设置私有type类变量,您需要在构造函数中或在创建对象之后但在调用type方法之前调用toString方法。例如

public Lion(int numTeeth, boolean spots, int weight) {
    super(numTeeth, spots, weight);
    type(weight);
}

请注意,如注释中所指出的那样,直接使用type方法处理setWeight可能会更好。您可以做类似的事情

@Override
public void setWeight(int weight) {
    super.setWeight(weight);
    type(weight);
}

并且不理会构造函数。

再进一步,您可以重构代码,使type方法没有参数(您已经设置了weight成员)。