首页 > 解决方案 > Java继承-子类方法覆盖

问题描述

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

我得到了一个 Animal.java 类。我的作业是创建一个名为 Lion.java 的子类。我在整个任务中苦苦挣扎的任务之一是根据狮子的重量输出狮子的类型。这是 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 语句返回类型。这可能是一个非常简单的解决方案,但我似乎无法弄清楚。

标签: java

解决方案


好好看看你的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成员)。


推荐阅读