Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is super class constructor always called [duplicate]

I have the following 2 classes

public class classA {     classA() {         System.out.println("A");     } }  class classB extends classA {     classB() {         System.out.println("B");     } } 

and then running

1

classA c = new classB(); 

or

2

classB c = new classB();  

always gives

A B 

Why is this happening? At first glance, in either scenario, I would assume that only the classB constructor would be called and thus the only output would be

B 

but this is clearly wrong.

like image 433
rgarci0959 Avatar asked Dec 28 '15 06:12

rgarci0959


People also ask

Is super class constructor always called?

Super class constructor is always called during construction process and it's guaranteed that super class construction is finished before subclass constructor is called.

Why do we call super constructor?

We use super keyword to call the members of the Superclass. As a subclass inherits all the members (fields, methods, nested classes) from its parent and since Constructors are NOT members (They don't belong to objects. They are responsible for creating objects), they are NOT inherited by subclasses.

Why super constructor is the first statement?

The Sun compiler says, call to super must be first statement in constructor . The Eclipse compiler says, Constructor call must be the first statement in a constructor . So, it is not stopping you from executing logic before the call to super() .

What happens if a super class doesn't have a constructor?

9: when no constructors are explicitly declared, a default constructor will be implicitly declared. This has the same access modifier as the class, and take no arguments.


1 Answers

That is how Java works. The constructors of the parent classes are called, all the way up the class hierarchy through Object, before the child class's constructor is called.

Quoting from the docs:

With super(), the superclass no-argument constructor is called. With super(parameter list), the superclass constructor with a matching parameter list is called.

Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem.

If a subclass constructor invokes a constructor of its superclass, either explicitly or implicitly, you might think that there will be a whole chain of constructors called, all the way back to the constructor of Object. In fact, this is the case. It is called constructor chaining, and you need to be aware of it when there is a long line of class descent.

like image 167
Aniket Thakur Avatar answered Oct 08 '22 22:10

Aniket Thakur