Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is super() the only code that can be implicit inserted in constructors if needed?

Tags:

java

I am trying to understand the Java compiler a little bit about the constructors. I know there are lots of topics about the super keyword in Java.

My main focus aspect of super key word in this question are:

Does the Java compiler implicitly generates some other constructors apart from default one (super()), for example: super(args1, args2)?

and can this statement be true?

I am 100% sure that super() is the only code that the Java compiler will insert to a constructor if the constructor does not have super or this in the first statement?

like image 435
Steven Avatar asked Dec 31 '22 00:12

Steven


2 Answers

Compiler will, by default, generate a call to super() constructor within your sub-class constructor, as a first statement, and that's the only thing it will implicitly do for you regarding your question.

If the super-class doesn't have a default constructor, then you must explicitly call to a whichever constructor is available for you (and which you wish among available ones) in the constructor of your subclass.

like image 98
Giorgi Tsiklauri Avatar answered Feb 08 '23 06:02

Giorgi Tsiklauri


Answer to your question:

"Does Java compiler has cases that it implicit inserts something else like super(args1, args2) in constructors?"

Ans:- No, you need to add manually.

"I am 100% sure that super() is the only code that the Java compiler will insert to a constructor if the constructor does not have super or this in the first statement"?

And:- default constructor of the parent class is implicit added by the compiler. If it required and not present.

Please read line by line details provided in the link of Java Doc

like image 39
Ashish Karn Avatar answered Feb 08 '23 06:02

Ashish Karn