看板java
標 題請問一下關於建構子的覆載
發信站不良牛牧場 (Tue Mar 7 22:01:54 2006)
轉信站ptt!ctu-reader!Spring!news.nctu!news.ntu!news.au!zoonews.ee.ntu!SimFar
我照著書上的範例打的程式:
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》 ◣◣◢ ─╯