Java 继承与多态:子类方法重写调用示例
以下是您提供的Java代码:
class Parent {
void display() {
System.out.println('This is the parent.');
}
}
class Child extends Parent {
@Override
void display() {
System.out.println('This is the child.');
}
}
public class Main {
public static void main(String[] args) {
Parent obj = new Child();
obj.display();
}
}
在这段代码中,obj.display()将调用子类Child中的display方法。这是因为在main方法中,我们创建了一个Parent类的引用obj,并将其指向Child类的实例。
由于Child类继承自Parent类,并重写了display方法,所以在运行时,调用的是子类的display方法。这被称为动态方法调度或运行时多态性。
因此,运行这段代码将会输出:'This is the child.'
原文地址: https://www.cveoy.top/t/topic/pSa 著作权归作者所有。请勿转载和采集!