2013-11-02 68 views
0

我想修改第一個類動物的構造函數,也是給定程序的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() ; 

    } 
} 

回答

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 = "";   
} 

代替,但因爲你似乎使用來創建對象單參數構造函數,不要用這個替換provious構造函數。相反,添加2個參數的構造函數。

+0

快5秒:) –

+0

更糟;),但你是對的,一次。 –

+0

非常感謝你 –

0

你必須將參數添加到構造函數:

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

非常感謝你 –

+0

@CashVai不客氣。請點擊他答案旁邊的綠色複選標記,接受R.J的回答:) –

+0

你去了哪裏! :) –