【发布时间】:2016-03-19 07:14:45
【问题描述】:
以此为例:
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 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.move() 方法时“Dog 类下的move()”方法已经覆盖了“Animal 类下的move()”方法,因为在调用相同方法时 Dog 对象优先何时被 Animal 类型引用?
我注意到许多网站并没有解释这一点,而是直接抛出示例而不逐行讨论。只是想澄清我的术语混乱。
附带说明,是否可以有一个 Dog 对象但调用 Animal 类下的 move() ?例如有类似的东西:
Dog doggy = new Dog();
doggy.move()
>>>
Animals can move
>>>
这可能吗? ((Animal) doggy).move() 会做到这一点吗?
【问题讨论】:
-
另外使用@Override 表示法,它可以防止你犯错误,比如在子类中拼错方法名。
标签: java terminology overriding