Java

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

小亿
109
2023-11-03 01:31:18
栏目: 编程语言

在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() method
Child class display() method

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

0
看了该问题的人还看了