使用关键字super
原文: https://docs.oracle.com/javase/tutorial/java/IandI/super.html
访问超类成员
如果您的方法覆盖了其超类的方法之一,则可以通过使用关键字super
来调用重写方法。您也可以使用super
来引用隐藏字段(尽管不鼓励隐藏字段)。考虑这个类,Superclass
:
public class Superclass {
public void printMethod() {
System.out.println("Printed in Superclass.");
}
}
这是一个名为Subclass
的子类,它覆盖了printMethod()
:
public class Subclass extends Superclass {
// overrides printMethod in Superclass
public void printMethod() {
super.printMethod();
System.out.println("Printed in Subclass");
}
public static void main(String[] args) {
Subclass s = new Subclass();
s.printMethod();
}
}
在Subclass
中,简单名称printMethod()
是指在Subclass
中声明的名称,它将覆盖Superclass
中的名称。因此,要引用从Superclass
继承的printMethod()
,Subclass
必须使用限定名称,如图所示使用super
。编译和执行Subclass
将打印以下内容:
Printed in Superclass.
Printed in Subclass
子类构造器
以下示例说明如何使用super
关键字来调用超类的构造器。回想一下 Bicycle
的例子,MountainBike
是Bicycle
的子类。这是MountainBike
(子类)构造器,它调用超类构造器,然后添加自己的初始化代码:
public MountainBike(int startHeight,
int startCadence,
int startSpeed,
int startGear) {
super(startCadence, startSpeed, startGear);
seatHeight = startHeight;
}
调用超类构造器必须是子类构造器中的第一行。
调用超类构造器的语法是
super();
or:
super(parameter list);
使用super()
,将调用超类无参数构造器。使用super(parameter list)
,将调用具有匹配参数列表的超类构造器。
Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. Object
does have such a constructor, so if Object
is the only superclass, there is no problem.
如果子类构造器显式或隐式地调用其超类的构造器,您可能会认为将调用一整个构造器链,一直回到Object
的构造器。事实上,情况就是这样。它被称为构造器链接,当需要很长的类下降时你需要注意它。