【发布时间】:2016-08-07 09:59:02
【问题描述】:
超类引用变量可以保存子类对象,但使用该变量您只能访问超类的成员,因此要访问两个类的成员,建议始终为子类创建引用变量。
class Animal {
public void move() {
System.out.println("Animals can move");
}
}
class Dog extends Animal {
public void move() {
System.out.println("Dogs can walk and run");
}
public void bark() {
System.out.println("Dogs can bark");
}
}
public class TestDog {
public static void main(String args[]) {
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
a.move(); // runs the method in Animal class
b.move(); // runs the method in Dog class
b.bark();
}
}
输出:
TestDog.java:26: error: cannot find symbol
b.bark();
^
symbol: method bark()
location: variable b of type Animal
1 error
我在这里不明白的是为什么对象'b'能够访问 Dog.move() 而不是 Dog.bark() 因为上面提到的语句说它只能访问超类的成员而不是子类。按照这个逻辑,b.move() 的输出应该是“动物可以移动”而不是“狗可以走路和奔跑”。但事实并非如此。有人可以帮我吗?提前致谢!
【问题讨论】:
-
b.bark();是错误的,因为动物不会吠叫。需要向下转换,例如: ((Dog) b).bark();
标签: java inheritance overriding