class
Inheritance constructor calls example
With this example we are going to demonstrate how to inherit constructor calls from a super class to a sub class. In short, to inherit constructor calls from a super class to a sub class:
- We have created a class
A
, with a constructor and a classB
that extendsA
and also has a constructor. - We have also created class
Constructors
that extendsB
and also has its own constructor. - We create a new instance of
Constructors
, and as a result all inherited constructors are first called and then the classe’s constructor is also called.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; class A { A() { System.out.println("A constructor"); } } class B extends A { B() { System.out.println("B constructor"); } } public class Constructors extends B { public Constructors() { System.out.println("Public class constructor"); } public static void main(String[] args) { Constructors x = new Constructors(); } }
Output:
A constructor
B constructor
Public class constructor
This was an example of how to inherit constructor calls from a super class to a sub class in Java.