Java中的动态方法分派或运行时多态

Java中的运行时多态性是通过方法覆盖实现的,方法覆盖是子类覆盖其父类中的方法。重写的方法本质上隐藏在父类中,除非子类在重写的方法中使用super关键字,否则不会调用该方法。此方法调用解析在运行时发生,称为动态方法分派机制。

示例

让我们来看一个例子。

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
   }
}

这将产生以下结果-

输出结果

Animals can move
Dogs can walk and run

在上面的示例中,您可以看到,即使b是Animal的一种,它也会在Dog类中运行move方法。原因是:在编译时,对引用类型进行检查。但是,在运行时中,JVM会找出对象类型并运行属于该特定对象的方法。

因此,在上面的示例中,由于Animal类具有方法move,因此程序将正确编译。然后,在运行时,它将运行特定于该对象的方法。