請問一下關於建構子的覆載

看板java作者時間18年前 (2006/03/08 02:01), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串1/4 (看更多)
我照著書上的範例打的程式: public class Animal { private int legs; public Animal() { setLegs(4); } public Animal(int l) { setLegs(l); } public void eat() { System.out.println("Eating..."); } public void move() { System.out.println("Moving..."); } public void setLegs(int l) { if(l!=0 && l!=2 && l!=4) { System.out.println("Wrong number of legs!"); return; } legs=l; } public int getLegs() { return legs; } } public class Zoo { public static void main(String argv[]) { Animal animal1=new Animal(); Animal animal2=new Animal(); Animal animal3=new Animal(10); animal1.setLegs(3); animal2.setLegs(2); System.out.println("animal1 has "+animal1.getLegs()+"legs."); System.out.println("animal2 has "+animal2.getLegs()+"legs."); System.out.println("animal3 has "+animal3.getLegs()+"legs."); } } 執行結果是 Wrong number of legs! Wrong number of legs! animal1 has 4 legs. animal1 has 2 legs. animal1 has 0 legs. 跟書上的結果一樣,但是書上卻說只有animal2的legs數有設定成功,所以顯示是2 其餘animal1和animal3的legs都是0 跟run出來的結果為什麼不一樣呢? 請各位大大解答一下,謝謝! -- ╭──── Origin:<不良牛牧場> bbs.badcow.com.tw (210.200.247.200)─────╮ Welcome to SimFarm BBS -- From : [210.192.201.234] ◣◣◢ ◢◢不良牛免費撥接→電話:40586000→帳號:zoo→密碼:zoo ◣◣─╯
文章代碼(AID): #143Sf_00 (java)
文章代碼(AID): #143Sf_00 (java)