3 回答
TA贡献1811条经验 获得超5个赞
你的家猫有两个构造器:
// one constructor
HouseCat(){
this.cType = "Short Hair";
}
// another constructor
public HouseCat(String name, double weight, String mood, String cType) {
super(name, weight, mood);
if(cType.equalsIgnoreCase("Short Hair")||cType.equalsIgnoreCase("Bombay")||cType.equalsIgnoreCase("Ragdoll")||cType.equalsIgnoreCase("Sphinx")||cType.equalsIgnoreCase("Scottish Fold")) {
this.setCType(cType);
}
else {
System.out.println("Invalid type");
}
}
您在前端调用具有 4 个参数的构造函数,而不是无参数构造函数,因此从未运行过。this.cType = "Short Hair";
同样的事情发生在 - 你用3个参数调用构造函数,而不是设置为默认值的无参数构造函数。Catmood
要解决此问题,只需删除无参数构造函数,然后以内联方式初始化变量:
// in HouseCat
public String cType = "Short Hair"; // btw you shouldn't use public fields.
// in Cat
public String mood = "Sleepy";
TA贡献1796条经验 获得超10个赞
当您创建名为参数化的对象时,在默认构造函数中,您初始化了这些对象,这就是为什么这些是空的。HouseCatConstructorTypeMood
您需要在参数化中设置这些值,然后它们将显示您的显式输出。像构造函数 sholud 一样被修改ConstructorHousecat
public HouseCat(String name, double weight, String mood, String cType) {
super(name, weight, mood);
if(cType.equalsIgnoreCase("Short Hair")||cType.equalsIgnoreCase("Bombay")||cType.equalsIgnoreCase("Ragdoll")||cType.equalsIgnoreCase("Sphinx")||cType.equalsIgnoreCase("Scottish Fold")) {
this.setCType(cType);
}
else {
System.out.println("Invalid type");
this.cType = "Short Hair";//<------------- set default value here
}
}
和构造函数应该像Cat
public Cat(String name, double weight, String mood) {
super(name, weight);
if(mood.equalsIgnoreCase("sleepy")||mood.equalsIgnoreCase("playful")||mood.equalsIgnoreCase("hungry")) {
this.setMood(mood);
}
else {
System.out.println("Invalid mood");
this.mood = "Sleepy";//<------------- set default value here
}
}
TA贡献1830条经验 获得超9个赞
您在 Cat 类中创建了两个构造函数:
Cat(){
this.mood = "Sleepy";
}
和
public Cat(String name, double weight, String mood) {
super(name, weight);
if(mood.equalsIgnoreCase("sleepy")||mood.equalsIgnoreCase("playful")||mood.equalsIgnoreCase("hungry")) {
this.setMood(mood);
}
else {
System.out.println("Invalid mood");
}
}
只有第一个(没有参数)初始化情绪字段。您显然使用另一个来创建您的实例...
你有多个解决方案:1.删除未使用的构造函数并在另一个构造函数中引发情绪 2.将未使用的构造函数更改为“简单”方法,您将在构造函数 3 中立即调用该方法。...super
例:
public Cat(String name, double weight, String mood) {
super(name, weight);
this.mood = "Sleepy";
if(mood.equalsIgnoreCase("sleepy")||mood.equalsIgnoreCase("playful")||mood.equalsIgnoreCase("hungry")) {
this.setMood(mood);
}
else {
System.out.println("Invalid mood");
}
}
添加回答
举报