在Java中,要在子类中调用父类的方法,您可以使用super关键字。super关键字允许您访问父类的方法和构造函数。以下是如何使用super关键字调用父类方法的示例:
display的方法:class Parent {
void display() {
System.out.println("This is the Parent class method.");
}
}
Parent类的子类,并在其中添加一个名为display的方法。在这个方法中,使用super关键字调用父类的display方法:class Child extends Parent {
void display() {
super.display(); // 调用父类的display方法
System.out.println("This is the Child class method.");
}
}
Child对象,并调用其display方法:public class Main {
public static void main(String[] args) {
Child child = new Child();
child.display();
}
}
当您运行此程序时,将看到以下输出:
This is the Parent class method.
This is the Child class method.
这表明子类的display方法已成功调用了父类的display方法。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。