java - 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 语句返回类型。这可能是一个非常简单的解决方案,但我似乎无法弄清楚。
解决方案
好好看看你的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
成员)。
推荐阅读
- python - Tkinter python,无法从缩放对象中获取值
- sql-server - 可以从 SQL Server 数据库中的存储过程运行 Linux 脚本吗?
- csv - ANSI 编码的 CSV 文件由 VSCode 以 UTF8 重新编码。如何回到ANSI?
- node.js - 使用 babel NodeJs 进行模块化
- oauth-2.0 - 特定于资源的 OAuth2 授权的常见做法?
- python - Numpy 切片数组内存消耗
- javascript - 有没有更简洁的方法来检查是否存在深层嵌套节点?
- python - 如果行值在python中的x之间,则替换整个列
- mysql - 递归sql查询中的无限循环
- saleor - 我们如何在 Saleor 仪表板中翻译产品属性?