Java 中的 super 用于访问父类的方法和成员变量,主要用途包括调用父类构造函数、访问父类方法和访问父类变量。在子类中使用 super() 调用父类构造函数,super.methodName() 访问父类方法,super.variableName 访问父类变量。注意:super 只能在子类中使用,必须作为语句的第一行。
Java 中的 super
super 在 Java 中是一个关键字,用于访问父类的方法和成员变量。
用途
super 主要有以下几种用途:
示例
以下示例展示了 super 的使用方法:
class Parent {
public Parent() {
System.out.println("Parent constructor");
}
public void print() {
System.out.println("Parent method");
}
}
class Child extends Parent {
public Child() {
super(); // 调用父类构造函数
System.out.println("Child constructor");
}
@Override
public void print() {
super.print(); // 访问父类方法
System.out.println("Child method");
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
child.print(); // 输出:Parent constructor, Child constructor, Parent method, Child method
}
}注意事项