是否不必在构造函数中放置super()? [英] Is it unnecessary to put super() in constructor?

查看:134
本文介绍了是否不必在构造函数中放置super()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我不把它放在一个子类的构造函数中,编译器是不是自动放置这个?

Isn't this one automatically put by the compiler if I don't put it in a subclass's constructor?

这意味着我甚至不需要关心关于它?

That means I don't even need to care about it? In some articles they put it out.

如果我有一个带参数的构造函数,这将是构造函数,还是采用没有参数列表的构造函数?

And if I've got one constructor with arguments, will this be the constructor, or does it take a constructor without argument list?

推荐答案

首先是一些术语:


  • 无参数构造函数:没有参数的构造函数;

  • 可访问的无参数构造函数超类对子类可见。这意味着它是公共的或受保护的,或者,如果两个类都在同一个包中,包访问;

  • 默认构造函数:在类中没有显式构造函数时,编译器添加的public no-args构造函数。

  • No-args constructor: a constructor with no parameters;
  • Accessible no-args constructor: a no-args constructor in the superclass visible to the subclass. That means it is either public or protected or, if both classes are in the same package, package access; and
  • Default constructor: the public no-args constructor added by the compiler when there is no explicit constructor in the class.

所有类都至少有一个构造函数。

So all classes have at least one constructor.

子类构造函数 作为第一件事,他们在超类中在执行子类的构造函数中的代码之前调用它的构造函数。

Subclasses constructors may specify as the first thing they do which constructor in the superclass to invoke before executing the code in the subclass's constructor.

如果子类构造函数没有指定要调用的超类构造函数,编译器将自动调用超类中的可访问的无参数构造函数。

If the subclass constructor does not specify which superclass constructor to invoke then the compiler will automatically call the accessible no-args constructor in the superclass.

如果超类没有无参数构造函数或者不可访问,则不指定超类

If the superclass has no no-arg constructor or it isn't accessible then not specifying the superclass constructor to be called (in the subclass constructor) is a compiler error so it must be specified.

例如:

public class Base { }
public class Derived extends Base { }

这是很好的,因为如果你显式地添加没有构造函数Java放在公共默认构造函数中。

This is fine because if you add no constructor explicitly Java puts in a public default constructor for you.

public class Base { }
public class Derived extends Base { public Derived(int i) { } }

也很好。

public class Base { public Base(String s) { } }
public class Derived extends Base { }

上面是一个编译错误,没有默认构造函数。

The above is a compilation error as Base has no default constructor.

public class Base { private Base() { } }
public class Derived extends Base { }

这也是一个错误,因为Base的无参数构造函数是私有的。

This is also an error because Base's no-args constructor is private.

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

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