子类覆写了父类的方法
public class Test {
public static void main(String[] args) {
//Java的实例方法调用是基于运行时的实际类型的动态调用,而非变量的声明类型。
Person p = new Student();
p.run();
}
}
class Person {
public void run() {
System.out.println("Person.run");
}
}
class Student extends Person {
@Override
public void run() {
System.out.println("Student.run");
}
}
运行结果:(调用的方法是Student的run()方法)

该代码示例展示了Java中的多态性特性。Person类有一个run()方法,而Student类继承了Person并覆写了这个方法。在main方法中,虽然变量p声明为Person类型,但实际创建的是Student对象。因此,调用p.run()会执行Student的run()方法,体现出运行时动态绑定的概念。
3万+

被折叠的 条评论
为什么被折叠?



