Why do we call super() in the constructor? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 5

Why do we call super() in the constructor?

super class and constructors

26th Jan 2018, 9:44 PM
Nazar Ahmed Amjad
Nazar Ahmed Amjad - avatar
2 Answers
+ 8
Using super() in a child class constructor makes you use the parent class constructor before invoking the child class constructor code. The thing is, this happens implicitly anyway - whenever you instantiate a child class the parent class is constructed first, so in this case using super() or not yields the same result, effectively the compiler does this for you, just as it generates a default constructor if you haven't coded one. This becomes important when you have multiple constructors in either class. Suppose that in the parent class you have two constructors with one and two parameters respectively. If you try to create a constructor in a child class it will complain with an error saying that no default constructor exists for the parent class. In this case you MUST specify a constructor to use, by using something like super(param1) etc. (This need not correspond with the number of parameters the particular constructor in the child class is calling).
26th Jan 2018, 10:26 PM
Dan Walker
Dan Walker - avatar
+ 9
you can use super if you want to use constuctor that you have in superclass of that class
26th Jan 2018, 10:12 PM
Vukan
Vukan - avatar