看板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》 ◣◣◢ ─╯