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 字段未在此构造函数中初始化。您还应该调用第二个构造函数。
添加回答
举报