Java运行时多态与多层继承
方法重写 是 运行时多态 的一个例子。在方法重写中,子类重写了与其超类中方法签名相同的方法。在编译时,检查是在引用类型上进行的。然而,在运行时,JVM 会确定对象的类型,并运行属于该特定对象的方法。
问题陈述
使用 Java 中的 多层继承 和方法重写来演示运行时多态。
输出
Animals can move Puppy can move.
朴素方法
以下是使用多层继承在 Java 中实现运行时多态的步骤:
- 步骤 1: 定义一个带有 move() 方法的 Animal 类。
- 步骤 2: 创建一个继承自 Animal 并重写 move() 方法的 Dog 类。
- 步骤 3: 创建一个继承自 Dog 并重写 move() 方法的 Puppy 类。
- 步骤 4: 在主方法中,创建一个 Animal 引用和对象,以及一个带有 Puppy 对象的 Animal 引用。
- 步骤 5: 在这两个引用上调用 move() 方法以演示运行时多态。
使用多层继承实现运行时多态的示例
我们可以在多层继承的任何级别重写方法。请参阅下面的示例以了解此概念:
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");
}
}
class Puppy extends Dog {
public void move() {
System.out.println("Puppy can move.");
}
}
public class Tester {
public static void main(String args[]) {
Animal a = new Animal(); // Animal reference and object
Animal b = new Puppy(); // Animal reference but Puppy object
a.move(); // runs the method in Animal class
b.move(); // runs the method in Puppy class
}
}
输出
Animals can move Puppy can move.
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP