3 回答

TA貢獻1811條經驗 獲得超6個贊
你的家貓有兩個構造器:
// 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");
}
}
添加回答
舉報