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 婆婆高寿祝福语大全简短