简体   繁体   中英

Calling super() on a class with no constructor

I just noticed in the codebase of a very large project I am assigned at work, a particular class has no constructor. Its subclass though, calls super() .

Can someone please explain what is going when a subclass calls super() , but there is no constructor in the parent?

(I can guess that the effect is like calling an empty constructor, but I am wondering if there is anything else going on behind the scenes).

If you do not have any parameterized constructor and I strictly mean no constructor then and only then java will add a default constructor(One with no parameters) for you.

Each constructor must call a constructor of it's super class. You cannot perform any other action in the subclass constructor untill all constructors of superclasses up the inheritance tree are called. Hence this call must be the 1st line of your subclass constructor If you do not provide one again java does that for you.

Refer

Why does this() and super() have to be the first statement in a constructor?

If a class doesnt having any constructors means it is gifted with empty constructor by the java compiler.

If you place the empty constructor , then the compiler will not because it is already mentioned by you.

Now If you want your own constructor with your own parameters, Then there will not be any default constructor by the java compiler

Check this for more info on constructors

Subclass constructor always call its parent constructor first before executing any statement. If there is no consturctor in parent class then whether you call it or not explicitly, super() call will be added in the code by java compiler and hence will be executed by JVM.

The java compiler will provide a default no argument constructor without a body when a class doesn't declare any constructors. Calling super() in a base class constructor will invoke that default constructor.

Can someone please explain what is going when a subclass calls super(), but there is no constructor in the parent?

If parent class doesn't have any constructor then java compiler will call the default constructor of it. If you don't want to call default constructor then you can create your own empty constructor in that class.

Compiler add a default constructor with no parameter into your class if you do not provide it explicitly. So in your case it is calling default constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM