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");
}
}
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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP