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 class B that extends A and also has a constructor.
  • We have also created class Constructors that extends B 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.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button