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

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

问题描述:

我正在处理一个扩展 JFrame 的类.

I'm dealing with a class which extends JFrame.

这不是我的代码,它在开始构建 GUI 之前调用了 super.我想知道为什么要这样做,因为我总是只访问超类的方法而不必调用 super();

It's not my code and it makes a call to super before it begins constructing the GUI. I'm wondering why this is done since I've always just accessed the methods of the superclass without having to call super();

有一个对 super() 的隐式调用,对于所有具有父级的类没有参数 - 这是每个用户定义的类在 Java 中 - 所以通常不需要显式调用它.但是,如果父的构造函数接受参数,并且您希望指定它们,您可以使用带有参数的对 super() 的调用.此外,如果父的构造函数接受参数,并且没有默认的无参数构造函数,您将需要用参数调用super().

There is an implicit call to super() with no arguments for all classes that have a parent - which is every user defined class in Java - so calling it explicitly is usually not required. However, you may use the call to super() with arguments if the parent's constructor takes parameters, and you wish to specify them. Moreover, if the parent's constructor takes parameters, and it has no default parameter-less constructor, you will need to call super() with argument(s).

一个例子,显式调用 super() 可以让你对框架的标题有一些额外的控制:

An example, where the explicit call to super() gives you some extra control over the title of the frame:

class MyFrame extends JFrame
{
    public MyFrame() {
        super("My Window Title");
        ...
    }
}