使用关键字super

原文: https://docs.oracle.com/javase/tutorial/java/IandI/super.html

访问超类成员

如果您的方法覆盖了其超类的方法之一,则可以通过使用关键字super来调用重写方法。您也可以使用super来引用隐藏字段(尽管不鼓励隐藏字段)。考虑这个类,Superclass

  1. public class Superclass {
  2. public void printMethod() {
  3. System.out.println("Printed in Superclass.");
  4. }
  5. }

这是一个名为Subclass的子类,它覆盖了printMethod()

  1. public class Subclass extends Superclass {
  2. // overrides printMethod in Superclass
  3. public void printMethod() {
  4. super.printMethod();
  5. System.out.println("Printed in Subclass");
  6. }
  7. public static void main(String[] args) {
  8. Subclass s = new Subclass();
  9. s.printMethod();
  10. }
  11. }

Subclass中,简单名称printMethod()是指在Subclass中声明的名称,它将覆盖Superclass中的名称。因此,要引用从Superclass继承的printMethod()Subclass必须使用限定名称,如图所示使用super。编译和执行Subclass将打印以下内容:

  1. Printed in Superclass.
  2. Printed in Subclass

子类构造器

以下示例说明如何使用super关键字来调用超类的构造器。回想一下 Bicycle 的例子,MountainBikeBicycle的子类。这是MountainBike(子类)构造器,它调用超类构造器,然后添加自己的初始化代码:

  1. public MountainBike(int startHeight,
  2. int startCadence,
  3. int startSpeed,
  4. int startGear) {
  5. super(startCadence, startSpeed, startGear);
  6. seatHeight = startHeight;
  7. }

调用超类构造器必须是子类构造器中的第一行。

调用超类构造器的语法是

  1. super();

or:

  1. 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的构造器。事实上,情况就是这样。它被称为构造器链接,当需要很长的类下降时你需要注意它。