调用super() [英] Calling super()

查看:113
本文介绍了调用super()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你什么时候用Java调用super()?
我在派生类的一些构造函数中看到它,但不是自动调用的每个父类的构造函数?为什么你需要使用超级?

When do you call super() in Java? I see it in some constructors of the derived class, but isn't the constructors for each of the parent class called automatically? Why would you need to use super?

推荐答案

如果你提供这样的课程:

If you provide a class like this:

public class Foo
{
}

或者这个:

public class Foo()
{
    public Foo()
    {
    }
}

编译器将生成代码:

public class Foo()
{
    public Foo()
    {
        super();
    }
}

所以,严格来说,调用super( )总是在那里。

So, strictly speaking, the call to "super()" is always there.

在实践中,你应该只调用super(...),其中有你想传递给父构造函数的参数。

In practice you should only call "super(...)" where there are parameters you want to pass to the parent constructor.

调用super()(没有参数)没有错,但人们会嘲笑你: - )

It isn't wrong to call "super()" (with no parameters) but people will laugh at you :-)

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

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