我想修改第一個類動物的構造函數,也是給定程序的make_speak方法,所以它會打印出如下所示:「你好,我是一個貓叫路德維希我已經吃了。......」我有一個關於java面向對象編程的問題(初學者)
類動物的第一個構造有這樣的動物對象可通過書面形式創建的方式來修改:
Animal named_cat = new Animal("cat", "Ludwig") ;
我的問題:什麼是我做錯了修改類動物(或其他部分)的第一個構造函數。謝謝!
這裏是我的修改方案:
class Animal
{
String species_name ;
String stomach_contents ;
\\ here I added the String animal_name
String animal_name;
public Animal(String given_species_name)
{
species_name = given_species_name;
animal_name = given_animal_name;
stomach_contents = "" ;
}
public Animal(Animal another_animal)
{
species_name = another_animal.species_name ;
stomach_contents = another_animal.stomach_contents ;
}
public void feed(String food_for_this_animal)
{
stomach_contents =
stomach_contents + food_for_this_animal + ", " ;
}
public void make_speak()
{
System.out.print("\n Hello, I am a " + species_name + "called " + animal_name + "."
+ "\n I have eaten: " + stomach_contents + "\n") ;
}
public void make_stomach_empty()
{
stomach_contents = "" ;
}
}
class Animals
{
public static void main(String[] not_in_use)
{
Animal cat_object = new Animal("cat") ;
Animal named_cat = new Animal("cat", "Ludwig") ;
Animal dog_object = new Animal("vegetarian dog") ;
cat_object.feed("chicken") ;
cat_object.make_speak() ;
cat_object.make_stomach_empty();
dog_object.feed("salad");
dog_object.make_speak();
dog_object.make_stomach_empty();
Animal another_cat = new Animal(cat_object) ;
another_cat.feed("milk") ;
cat_object.make_speak() ;
dog_object.make_speak() ;
another_cat.make_speak() ;
}
}
快5秒:) –
更糟;),但你是對的,一次。 –
非常感謝你 –