具有多级继承的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
小狗可以移动。