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

查看:28
本文介绍了是否没有必要将 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?

推荐答案

首先是一些术语:

  • 无参数构造函数:一个没有参数的构造函数;
  • 可访问的无参数构造函数: 子类可见的超类中的无参数构造函数.这意味着它要么是公共的,要么是受保护的,或者,如果两个类都在同一个包中,则包访问;和
  • 默认构造函数:当类中没有显式构造函数时,编译器添加的公共无参数构造函数.
  • 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 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 { }

以上是编译错误,因为 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天全站免登陆