aman_novice aman_novice - 11 days ago 6
Java Question

Why is constructor of super class invoked when we declare the object of sub class? (Java)

Consider this code:

class Test {
Test() {
System.out.println("In constructor of Superclass");
}

int adds(int n1, int n2) {
return(n1+n2);
}

void print(int sum) {
System.out.println("the sums are " + sum);
}
}


class Test1 extends Test {
Test1(int n1, int n2) {
System.out.println("In constructor of Subclass");
int sum = this.adds(n1,n2);
this.print(sum);
}

public static void main(String[] args) {
Test1 a=new Test1(13,12);
Test c=new Test1(15,14);
}
}


If we have a constructor in super class, it will be invoked by every object tht we
construct for the child class(ex. Object 'a' for class Test1 calls Test1(int n1, int n2) as well as Test()).

Why does this happen?

The output of this program is:


In constructor of Superclass

In constructor of Subclass

the sums are 25

In constructor of Superclass

In constructor of Subclass

the sums are 29

Answer

Because it will ensure that when a constructor is invoked, it can rely on all the fields in its superclass being initialised.

see 3.4.4 in here