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
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短