我正在尝试修改动物类的第一个构造函数以及给定程序的 make_speak 方法,因此它将打印如下内容:“你好,我是一只名叫路德维希的猫。我吃过:......”
动物类的第一个构造函数必须以某种方式进行修改,以便可以通过以下方式创建动物对象:
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() ;
}
}