在main函数里,创建对象后,如果先调用方法然后调用属性,输出的属性值为空,为什么?
Animal 类:
public class Animal {
public int age;
public String name;
public void eat(){
System.out.println(name+":"+age);
System.out.println("animal can eat food");
}
}
Dog 类(继承Animal类):
public class Dog extends Animal {
}
入口类Main 函数:
public class TestAnimal {
public static void main(String[] args) {
// TODO Auto-generated method stub
Dog dog = new Dog();
dog.eat();
dog.name="beibie";
dog.age=2;
}
}
输出结果:null:0
animal can eat food
如果把dog.eat();移到dog.age=2;的下面,输出结果:
beibie:2
animal can eat food