Consider this code:
class Test {
Test() {
System.out.println(\"In constructor of Superclass\");
}
int adds(int n1, int n2) {
ret
Yes. A superclass must be constructed before a derived class could be constructed too, otherwise some fields that should be available in the derived class could be not initialized.
A little note: If you have to explicitly call the super class constructor and pass it some parameters:
baseClassConstructor(){
super(someParams);
}
then the super constructor must be the first method call into derived constructor. For example this won't compile:
baseClassConstructor(){
foo();
super(someParams); // compilation error
}
I'll try to answer this from a different perspective.
Suppose Java didn't call the super constructor for you automatically. If you inherit the class, you'd have to either call the super constructor implicitly, or rewrite it yourself. This would require you to have internal knowledge of how the super class works, which is bad. It would also require to to rewrite code, which is also not good.
I agree that calling the super constructor behind the scenes is a little unintuitive. On the other hand, I'm not sure how they could have done this in a more intuitive way.
In simple words if super class has parameterized constructor, you need to explicitly call super(params) in the first line of your child class constructor else implicitly all super class constructors are called untill object class is reachead.
There is a default super() call in your default constructors of sub classes.
//Default constructor of subClass
subClass() {
super();
}
Constructor of Super class in called first because all the methods in the program firstly present in heap and after compilation they stores in to the stack,due to which super class constructor is called first.
Java classes are instantiated in the following order:
(at classload time) 0. initializers for static members and static initializer blocks, in order of declaration.
(at each new object)