0

我正在尝试修改动物类的第一个构造函数以及给定程序的 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() ;

   }
}
4

2 回答 2

0

您需要在构造函数中有 2 个参数而不是 1 个。

public Animal( String  given_species_name, String given_animal_name) {
    species_name = given_species_name;
    animal_name = given_animal_name;
    stomach_contents = "";           
}

但是由于您似乎也在使用单参数构造函数创建一个对象,所以不要用这个替换之前的构造函数。相反,添加另一个带有 2 个参数的构造函数。

于 2013-11-02T12:12:54.130 回答
0

您必须将参数添加到构造函数:

public Animal( String  given_species_name, String given_animal_name ) {
  species_name      =  given_species_name;
  animal_name       =  given_animal_name;
  stomach_contents  =  "" ;           
}
于 2013-11-02T12:12:58.963 回答