5 回答

TA貢獻(xiàn)1942條經(jīng)驗(yàn) 獲得超3個(gè)贊
你打算做什么:
public Dog(String name, String breed, char sex, int age, double weight){
this("Chomp, chomp, chomp", "Woof, woof, woof");
this.name = name;
this.breed = breed;
this.sex = sex;
this.age = age;
this.weight = weight;
}
public Dog(String eating, String barking){
this.eating = eating;
this.barking = barking;
}
您需要調(diào)用構(gòu)造函數(shù)(使用this())設(shè)置這些值,因?yàn)樗粫?huì)自動(dòng)發(fā)生。

TA貢獻(xiàn)1876條經(jīng)驗(yàn) 獲得超5個(gè)贊
這是沒(méi)有意義的:
public Dog(String eating, String barking){
this.eating = "Chomp, chomp, chomp";
this.barking = "Woof, woof, woof";
}
參數(shù)不用于對(duì)字段進(jìn)行賦值:實(shí)際上,您對(duì)具有一些編譯時(shí)常量值的字段進(jìn)行賦值:“Chomp, chomp, chomp”和“Woof, woof, woof”。
根據(jù)您陳述的問(wèn)題,您認(rèn)為 any和字段Dog
具有默認(rèn)值: eating
barking
我應(yīng)該得到“當(dāng) Dog1 吃東西時(shí),它會(huì)發(fā)出咀嚼、咀嚼、咀嚼的聲音,而當(dāng)它吠叫時(shí),發(fā)出的聲音是汪汪汪汪汪汪”
Dog dog1 = new Dog ("Luca", "mutt", 'M', 22, 5 );
在這種情況下,一種更簡(jiǎn)單的方法是使用字段初始值設(shè)定項(xiàng)來(lái)為這些字段賦值。另一種方法:鏈接構(gòu)造函數(shù)(在西蒙的回答中提供)也是正確的,但這里我們不是在耦合構(gòu)造函數(shù)的情況下。所以你可以做得更簡(jiǎn)單。
private String eating = "Chomp, chomp, chomp";
private String barking = "Woof, woof, woof";
public Dog(String name, String breed, char sex, int age, double weight){
this.name = name;
this.breed = breed;
this.sex = sex;
this.age = age;
this.weight = weight;
}

TA貢獻(xiàn)1155條經(jīng)驗(yàn) 獲得超0個(gè)贊
我建議您在第一個(gè)構(gòu)造函數(shù)本身中設(shè)置進(jìn)食和吠叫并刪除第二個(gè)構(gòu)造函數(shù),因?yàn)槿魏?Dog 都會(huì)發(fā)出相同的聲音,并且在我看來(lái)?yè)碛羞@樣的構(gòu)造函數(shù)沒(méi)有意義
public Dog(String name, String breed, char sex, int age, double weight){
this.name = name;
this.breed = breed;
this.sex = sex;
this.age = age;
this.weight = weight;
this.eating = "Chomp, chomp, chomp";
this.barking = "Woof, woof, woof"
}

TA貢獻(xiàn)1906條經(jīng)驗(yàn) 獲得超10個(gè)贊
您在 eating and barking 字段中得到 null ,因?yàn)槟谡{(diào)用該類的第一個(gè)構(gòu)造函數(shù),并且這些字段沒(méi)有分配任何值。您需要從第一個(gè)構(gòu)造函數(shù)調(diào)用第二個(gè)構(gòu)造函數(shù)。
public Dog(String name, String breed, char sex, int age, double weight){
this("", "");
this.name = name;
this.breed = breed;
this.sex = sex;
this.age = age;
this.weight = weight;
}
最好創(chuàng)建一個(gè)包含所有字段的構(gòu)造函數(shù),并從具有特定值的其他構(gòu)造函數(shù)調(diào)用該構(gòu)造函數(shù)。
public Dog(String name, String breed, char sex, int age, double weight, String eating, String barking){
this("", "");
this.name = name;
this.breed = breed;
this.sex = sex;
this.age = age;
this.weight = weight;
this.eating = eating;
this.barking = barking;
}
public Dog(String name, String breed, char sex, int age, double weight){
this(name, breed, sex, age, weight, "", "");
}

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超7個(gè)贊
問(wèn)題是 dog1 對(duì)象是用第一個(gè) Dog 構(gòu)造函數(shù)創(chuàng)建的
public Dog(String name, String breed, char sex, int age, double weight){
this.name = name;
this.breed = breed;
this.sex = sex;
this.age = age;
this.weight = weight;
}
eating 和 barking 字段未在此構(gòu)造函數(shù)中初始化。您還應(yīng)該調(diào)用第二個(gè)構(gòu)造函數(shù)。
添加回答
舉報(bào)