java - 扩展动物的猎豹类。爪哇
问题描述
Cheetah 扩展程序不会运行。它提供了所有的狮子输出。但是猎豹不会输出。它运行良好,因为它没有错误,它只是绕过了 cheetah 继承并且不会输出它。
为此任务修改现有的 Animal.java 文件。
- 创建一个名为“Cheetah”的类:
- 继承自 Animal 类。
- 使用至少一个需要静态 setter 和 getter 的静态字段。
- 包含一个构造函数。
- 包含一个 toString() 方法。
- 有一个数组作为它的字段之一。
- 创建一个应用程序类,并在其中创建一个 Cheetah 对象并使用 main 方法打印出来。
所有的一切都在那里,猎豹就不会跑了。
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);
}
public static void main1(String[] args){
Cheetah cheetah = new Cheetah(30, true, 45);
System.out.println(cheetah);
}
}
狮子班
class Lion extends Animal {
String type = "";
public Lion(int numTeeth, boolean spots, int weight) {
super(numTeeth, spots, weight);
type(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;
}
}
猎豹类:
class Cheetah extends Animal {
public Cheetah(int numTeeth, boolean spots, int weight) {
super(numTeeth, spots, weight);
}
public String toString(String cheetah) {
String output = "Number of Teeth: " + getNumTeeth();
output += "\nDoes it have spots?: " + getSpots();
output += "\nHow much does it weigh: " + getWeight();
output += "\nCheetah";
return output;
}
}
解决方案
从您的代码中删除 main1 方法并像这样编辑您的 main 方法:
public static void main(String[] args){Lion lion = new Lion(30, false, 80);System.out.println(lion);Cheetah cheetah = new Cheetah(30, true, 45);System.out.println(cheetah);
}
推荐阅读
- javascript - 在 ES7 的类方法中使用 this 关键字
- ms-access - 表 B 弹出窗口在表 A 的第二次尝试时或之后未更新
- aws-lambda - AWS Chalice:多个 python 文件中的路由
- android - Android Studio Google Drive AppFolder 备份和恢复(数据库文件)
- java - jsp 3、jstl 1.2 和 Maven
- google-app-engine - 在 GAE 上部署的 Lumen App 无法连接到 cloud-sql 中的数据库
- java - 多态字符串反序列化
- python - 五分位数错误
- java - 使用 Java 向 HP 4515 打印机发送 PJL 命令
- php - 从本周星期一 18:00 选择值