具有多级继承的Java运行时多态
方法覆盖是运行时多态性的一个示例。在方法覆盖中,子类覆盖具有与其父类相同签名的方法。在编译期间,将对引用类型进行检查。但是,在运行时中,JVM会找出对象类型并运行属于该特定对象的方法。
我们可以覆盖任何级别的多级继承中的方法。请参阅以下示例以了解概念-
示例
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");
}
}
class Puppy extends Dog {
public void move() {
System.out.println("小狗可以移动。");
}
}
public class Tester {
public static void main(String args[]) {
Animal a = new Animal(); // Animal reference and object
Animal b = new Puppy(); // Animal reference but Puppy object
a.move(); // runs the method in Animal class
b.move(); // runs the method in Puppy class
}
}输出结果
Animals can move 小狗可以移动。
热门推荐
1 训练狗狗基础
2 怎么训练狗狗笑
3 怎么训练狗狗卧下
4 上海狗狗训练基地
5 训练狗狗排便
6 狗狗基础训练
8 如何训练狗狗装死
9 狗狗站姿训练
10 狗狗训练用品
11 训练狗狗吧
12 狗狗要怎么训练
13 怎么训练狗狗玩球
14 训练狗狗唤回
15 狗狗训练躺下
16 狗狗训练指令
17 狗狗的训练技巧
18 狗狗不好训练