为什么我们在构造函数中调用 super()

Why do we call super() in constructor

我们有这样一个构造函数:

public statusArea()     
{           
   super();         
   add(pageIdentifier);     
}

为什么我们在里面调用super

super() 调用超类 class.

的无参数构造函数

在您的代码中它没有区别,因为如果您不这样做,编译器将隐式添加 super()。通常,如果您希望调用超级 class.

的特定构造函数,则可以显式调用超级 class 的构造函数

来自Oracle docs

With super(), the superclass no-argument constructor is called. With super(parameter list), the superclass constructor with a matching parameter list is called.

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.

超类构造函数的调用必须在子类构造函数的第一行。

调用超类构造函数的语法是

super(); // the superclass no-arg constructor is called

或:

super(params);//the superclass constructor with a matching params is called

注:

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.

Java 中 super 关键字的目的是允许您访问实例字段、实例方法或超级 class 的构造函数,class =] 延伸。

由于 Java 中的每个 class 都隐含地从 Object 扩展,因此在 class 的构造函数中调用 super() 不会 [=任何 class 中的 13=] 表示调用 Object class 中的无参数构造函数。

即使您没有将 super() 调用明确地放在构造函数中,编译器也会添加一个。

在这里你使用super()给父class(即这个扩展的class)一个初始化任何字段或变量的机会,这样你的子类就可以正常工作。例如,superclass 可能有一些您不会在 subclass 中使用的字段或变量,但 class 正常工作需要这些字段或变量。

在这种情况下,super() 调用 superclass 的无参数构造函数,即。您的 class 延伸的那个。

如果你调用super(...)带参数,那么superclass构造函数就会调用匹配的参数。

正如其他人所说,如果你自己不调用super(),编译器会调用它。

你只需要指定调用的构造函数,如果:

您想调用具有参数

的超级class构造函数

您想链接到同一 class 中的另一个构造函数而不是超级class 构造函数