3 回答

TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超6個(gè)贊
你的家貓有兩個(gè)構(gòu)造器:
// 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");
}
}
您在前端調(diào)用具有 4 個(gè)參數(shù)的構(gòu)造函數(shù),而不是無參數(shù)構(gòu)造函數(shù),因此從未運(yùn)行過。this.cType = "Short Hair";
同樣的事情發(fā)生在 - 你用3個(gè)參數(shù)調(diào)用構(gòu)造函數(shù),而不是設(shè)置為默認(rèn)值的無參數(shù)構(gòu)造函數(shù)。Catmood
要解決此問題,只需刪除無參數(shù)構(gòu)造函數(shù),然后以內(nèi)聯(lián)方式初始化變量:
// in HouseCat
public String cType = "Short Hair"; // btw you shouldn't use public fields.
// in Cat
public String mood = "Sleepy";

TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超10個(gè)贊
當(dāng)您創(chuàng)建名為參數(shù)化的對(duì)象時(shí),在默認(rèn)構(gòu)造函數(shù)中,您初始化了這些對(duì)象,這就是為什么這些是空的。HouseCatConstructorTypeMood
您需要在參數(shù)化中設(shè)置這些值,然后它們將顯示您的顯式輸出。像構(gòu)造函數(shù) 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
}
}
和構(gòu)造函數(shù)應(yīng)該像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貢獻(xiàn)1830條經(jīng)驗(yàn) 獲得超9個(gè)贊
您在 Cat 類中創(chuàng)建了兩個(gè)構(gòu)造函數(shù):
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");
}
}
只有第一個(gè)(沒有參數(shù))初始化情緒字段。您顯然使用另一個(gè)來創(chuàng)建您的實(shí)例...
你有多個(gè)解決方案:1.刪除未使用的構(gòu)造函數(shù)并在另一個(gè)構(gòu)造函數(shù)中引發(fā)情緒 2.將未使用的構(gòu)造函數(shù)更改為“簡單”方法,您將在構(gòu)造函數(shù) 3 中立即調(diào)用該方法。...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");
}
}
添加回答
舉報(bào)