以下Java代码中,obj.display()将调用Child类中重写的display方法。

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类的实例。

由于obj的类型为Parent,但它实际上指向的是一个Child对象,因此在调用obj.display()时,实际上会执行Child类中重写的display方法。

在Child类中的display方法中,我们打印输出'This is the child.'。

因此,运行这段代码将会输出:'This is the child.',表示调用的是Child类中重写的display方法。

Java 继承和方法重写:深入理解 obj.display() 调用问题

原文地址: https://www.cveoy.top/t/topic/pXh 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录