Why we need to call super() method in default constructor?? why we need to parent class constructor ?? why it is compulsory? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why we need to call super() method in default constructor?? why we need to parent class constructor ?? why it is compulsory?

9th Oct 2017, 9:20 AM
Ankit Singh Rawat
Ankit Singh Rawat - avatar
5 Answers
+ 12
Do you agree, that a child can only exist if it's parents existed before? Same for child and parent classes ;)
9th Oct 2017, 11:33 AM
Tashi N
Tashi N - avatar
+ 3
when we put super() into a subclass it explicitly calls the superclass constructor. If we omit the call with super() there will be an implicit call to the Object class constructor(in superclasses). because all classes inherit from the Object class. This occurs regardless of whether I put (in superclass)extends Object or not.
9th Oct 2017, 8:11 PM
Malkon F
Malkon F - avatar
+ 2
@tashi awesome answer
9th Oct 2017, 6:08 PM
Ankush Kumar
Ankush Kumar - avatar
+ 2
but answering your question , this is mandatory because basically the superclass needs to have your variables initialized. Imagine if a subclass is instantied and we are going to manipulate a protected variable that was not initialized with values that are expected. Bugs, errors, or vulnerabilities can happen. Furthermore it would break the paradigm of oop: the inheritance was not going to make sense.
9th Oct 2017, 8:59 PM
Malkon F
Malkon F - avatar
+ 1
thanks Tashi N 😊
9th Oct 2017, 6:11 PM
Ankit Singh Rawat
Ankit Singh Rawat - avatar