java中怎么用super调用父类方法

   2025-02-15 2440
核心提示:在Java中,可以使用super关键字调用父类的方法。调用父类方法的语法为:super.父类方法名(参数列表)。以下是一个示例代码:class

在Java中,可以使用super关键字调用父类的方法。调用父类方法的语法为:super.父类方法名(参数列表)。

以下是一个示例代码:

class Parent {    public void display() {        System.out.println("Parent class display() method");    }}class Child extends Parent {    @Override    public void display() {        super.display(); // 调用父类的display()方法        System.out.println("Child class display() method");    }}public class Main {    public static void main(String[] args) {        Child child = new Child();        child.display();    }}

输出结果为:

Parent class display() methodChild class display() method

在Child类的display()方法中,通过super.display()调用了父类的display()方法,然后再执行子类自己的逻辑。注意,使用super调用父类方法时,需要保证父类方法是可访问的(即不是private修饰的)。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言