闰冬秋拾
2016-07-19 22:05
//Animal类:
public class Animal {
public int age = 110;
public String name;
public void eat(){
System.out.println("动物具有吃东西的能力");
}
public Animal(){
System.out.println("Animal类执行");
age = 210;
}
}//dog类继承Animal类:
public class Dog extends Animal {
public Dog(){
System.out.println("Dog类执行了");
System.out.println("这里是dog的构造函数,现在Age of the Animal is:" + super.age);
}
public void eat(){
System.out.println("狗是可以吃东西的");
System.out.println("这里是dog类内的eat函数,现在Age of the Animal is:" + super.age);
}
}
//初始化类:
public class Initial {
public static void main(String[] args) {
// TODO Auto-generated method stub
Animal animal = new Animal();
System.out.println(animal.age);
Dog dog = new Dog();
dog.age=110;
dog.name="Bobby";
dog.eat();
}
}显示结果:
Animal类执行
210
Animal类执行
Dog类执行了
这里是dog的构造函数,现在Age of the Animal is:210
狗是可以吃东西的
这里是dog类内的eat函数,现在Age of the Animal is:110
为什么在eat函数里print年龄的时候,就是显示主函数给狗的年龄了?难道不应该是父类animal的年龄吗?求解。
dog类继承了animal类,dog类没有定义自己的age, 这种情况下Dog类和Animal类的age是同一个。
Java入门第二季
531292 学习 · 6327 问题
相似问题