Home » Core Java » class » Inheritance constructor calls example

About Ilias Tsagklis

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

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.

(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of