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
热门推荐
6 庆双节祝福语简短
10 公司28 周年祝福语简短
11 小红书平安祝福语简短
12 相恋人回去祝福语简短
13 带清的简短祝福语
14 妈妈祝福语简短16字
15 对航母的祝福语简短
16 男朋友新年祝福语简短
17 老师对学校祝福语简短
18 简短祝福语大全暖心