为什么在构造函数中调用 super() ? [英] Why call super() in a constructor?

查看:50
本文介绍了为什么在构造函数中调用 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");
        ...
    }
}

这篇关于为什么在构造函数中调用 super() ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆