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(9);
Animal animal2;
animal2=new Animal(2);System.out.println("animal1 has "+animal1.getLegs()+" legs.");
System.out.println("animal2 has "+animal2.getLegs()+" legs.");
animal1.eat();
animal2.move();
}
}运行结果:
Wrong number of legs!
animal1 has 0 legs.
animal2 has 2 legs.
Eating...
Moving...为何显示的是animal1 has 0 legs.
执行到Animal animal1=new Animal(9);
9!=0&&9!=2&&9!=4,再执行return吗?
不是animal1.getLegs()为一个不确定的值吗?

解决方案 »

  1.   

    先看看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(9);
    Animal animal2;
    animal2=new Animal(2);System.out.println("animal1 has "+animal1.getLegs()+" legs.");
    System.out.println("animal2 has "+animal2.getLegs()+" legs.");
    animal1.eat();
    animal2.move();
    }
      

  2.   

    很正常啊 int 类型默认是0 set的时候没有赋值,所以取到的就是0
      

  3.   

    if(l!=0&&l!=2&&l!=4) 

    System.out.println("Wrong number of legs!"); 
    return; 

    不是animal1.getLegs()为一个不确定的值吗?
    一般整数都是0,对象是null
      

  4.   

    所有的变量在使用前都必须进行初始化,运行时变量必须是用户自己初始化的.但对于类变量及实例变量,如果用户没有给它们赋值,JVM都会自动赋值的.byte short int long float double 都为0,当然是相应基本类型的0.//所以才会输出:0 legsboolean 默认赋值为false.其它非基本类型的自动赋值为null.
      

  5.   

    为何显示的是animal1 has 0 legs.
    因为 legs 是int类型,Java中JVM自动给没有初始化的int类型的成员变量付初值0.执行到Animal animal1=new Animal(9);
    9!=0&&9!=2&&9!=4,再执行return吗?
    这里会return,所以legs=l; 不执行。不是animal1.getLegs()为一个不确定的值吗?
    Class类型的付初值null.
      

  6.   

    所有的变量在使用前都必须进行初始化,运行时变量必须是用户自己初始化的. 但对于类变量及实例变量,如果用户没有给它们赋值,JVM都会自动赋值的. byte short int long float double 都为0,当然是相应基本类型的0.//所以才会输出:0 legs boolean 默认赋值为false. 其它非基本类型的自动赋值为null. 正解