Java Constructor Inheritance

Whenever any class is inherited in Java using extends keyword, the subclass calls the default constructor of its parent class, see below example of inheritance in default constructor classes:


package com.evaluatethecode;

public class DefaultConstructorInheritance {

public static void main(String[] args) {
new C();
}
}

class A {

A() {
System.out.println("Level 1");
}
}

class B extends A{
B() {
System.out.println("Level 2");

}
}

class C extends B {
C() {
System.out.println("Level 3");
}
}

Output:
Level 1
Level 2
Level 3


Default constructor exists implicitly in all class until there is no parameterized constructor in that class, once the parameterized constructor is created that class does not have default constructor, if we want default constructor along with parameterized one, then we have to explicitly define default constructor in that case. See below example of inheritance in parameterized constructor classes:



package com.evaluatethecode;

public class ParameterizedConstructorInheritance {
public static void main(String[] args) {
new C1();
}
}

class A1 {

A1() {
System.out.println("Default constructor");
}
A1(String val) {
System.out.println("Level 1");
}
}

class B1 extends A1{

B1(String val) {
System.out.println("Level 2 "+val);

}
}

class C1 extends B1 {
C1() {
super("Initialize parent constructor with super() as it does not have
        default constructor");
System.out.println("Level 3");
}
}

Output:
Default constructor
Level 2 Initialize parent constructor with super() as it does not have 
default constructor
Level 3

No comments:

Post a Comment