5 回答

TA貢獻1942條經驗 獲得超3個贊
你打算做什么:
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;
}
您需要調用構造函數(使用this())設置這些值,因為它不會自動發生。

TA貢獻1876條經驗 獲得超5個贊
這是沒有意義的:
public Dog(String eating, String barking){
this.eating = "Chomp, chomp, chomp";
this.barking = "Woof, woof, woof";
}
參數不用于對字段進行賦值:實際上,您對具有一些編譯時常量值的字段進行賦值:“Chomp, chomp, chomp”和“Woof, woof, woof”。
根據您陳述的問題,您認為 any和字段Dog
具有默認值: eating
barking
我應該得到“當 Dog1 吃東西時,它會發出咀嚼、咀嚼、咀嚼的聲音,而當它吠叫時,發出的聲音是汪汪汪汪汪汪”
Dog dog1 = new Dog ("Luca", "mutt", 'M', 22, 5 );
在這種情況下,一種更簡單的方法是使用字段初始值設定項來為這些字段賦值。另一種方法:鏈接構造函數(在西蒙的回答中提供)也是正確的,但這里我們不是在耦合構造函數的情況下。所以你可以做得更簡單。
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貢獻1155條經驗 獲得超0個贊
我建議您在第一個構造函數本身中設置進食和吠叫并刪除第二個構造函數,因為任何 Dog 都會發出相同的聲音,并且在我看來擁有這樣的構造函數沒有意義
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貢獻1906條經驗 獲得超10個贊
您在 eating and barking 字段中得到 null ,因為您正在調用該類的第一個構造函數,并且這些字段沒有分配任何值。您需要從第一個構造函數調用第二個構造函數。
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;
}
最好創建一個包含所有字段的構造函數,并從具有特定值的其他構造函數調用該構造函數。
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貢獻1804條經驗 獲得超7個贊
問題是 dog1 對象是用第一個 Dog 構造函數創建的
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 字段未在此構造函數中初始化。您還應該調用第二個構造函數。
添加回答
舉報