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 是动物类型,但它运行的是“狗狗”类中的 move 方法。原因是:在编译时,是对引用类型进行检查。然而,在运行时,JVM 找出对象类型,并将运行属于该特定对象的方法。
因此,在上例中,该程序会正确编译,因为“动物”类具有 move 方法。然后,在运行时,它将运行特定于该对象的方法。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP