Demonstrate constructors in a Multilevel Hierarchy in Java


Multilevel inheritance is when a class inherits a class which inherits another class. An example of this is class C inherits class B and class B in turn inherits class A.

A program that demonstrates constructors in a Multilevel Hierarchy in Java is given as follows:

Example

 Live Demo

class A {
   A() {
      System.out.println("This is constructor of class A");
   }
}
class B extends A {
   B() {
      System.out.println("This is constructor of class B");
   }
}
class C extends B {
   C() {
      System.out.println("This is constructor of class C");
   }
}
public class Demo {
   public static void main(String args[]) {
      C obj = new C();
   }
}

Output

This is constructor of class A
This is constructor of class B
This is constructor of class C

Now let us understand the above program.

The class A contains the constructor A(). The class B uses the extends keyword to inherit class A. It also contains the constructor B(). The class C uses the extends keyword to inherit class B. It contains the constructor C(). A code snippet which demonstrates this is as follows:

class A {
   A() {
      System.out.println("This is constructor of class A");
   }
}
class B extends A {
   B() {
      System.out.println("This is constructor of class B");
   }
}
class C extends B {
   C() {
      System.out.println("This is constructor of class C");
   }
}

In the main() method in class Demo, an object obj of class C is created. A code snippet which demonstrates this is as follows:

public class Demo {
   public static void main(String args[]) {
      C obj = new C();
   }
}

Arushi
Arushi

e

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements