Java中super关键字:调用被覆盖的父类方法

在Java中,当子类覆盖了父类的实例方法时,可以使用super关键字在子类方法中调用父类被覆盖的版本。

super关键字语法

super关键字后面跟着方法名和参数列表,用于指定要调用的父类方法:javasuper.方法名(参数列表);

示例:使用super调用父类的sayHello()方法

假设有一个父类Person和一个子类Student,子类Student覆盖了父类PersonsayHello()方法。javapublic class Person { public void sayHello() { System.out.println('Hello, I am a person.'); }}

public class Student extends Person { @Override public void sayHello() { super.sayHello(); // 调用父类Person的sayHello()方法 System.out.println('Hello, I am a student.'); }}

public class Main { public static void main(String[] args) { Student student = new Student(); student.sayHello(); }}

输出结果:

Hello, I am a person.Hello, I am a student.

在子类StudentsayHello()方法中:

  1. super.sayHello(); 首先调用了父类PersonsayHello()方法,输出了'Hello, I am a person.'。2. 然后执行子类自身sayHello()方法的代码,输出了'Hello, I am a student.'。

总结

通过使用super关键字,我们可以在子类中方便地调用父类被覆盖的方法,并在子类方法中对其进行扩展。这在实现继承关系和代码复用方面非常有用。

Java中super关键字:调用被覆盖的父类方法

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

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