class

Inheritance and constructors example

This is an example of inheritance constructors of classes. The example is described in short below:

  • We have created class A, class B that extends A and CClass that extends B.
  • Each class inherits the constructor of its super class to be initialized.
  • We create a new instance for CClass, using its constructor.
  • Since it inherits B‘s constructor that also inherits A‘s constructor all constructors are called.

Let’s take a look at the code snippet that follows:  
  

package com.javacodegeeks.snippets.core;

class A {

    A(int i) {

  System.out.println("A constructor");
    }
}


class B extends A {

    B(int i) {

  super(i);

  System.out.println("B constructor");
    }
}

public class CClass extends B {

    CClass() {

  super(11);

  System.out.println("CClass constructor");
    }

    public static void main(String[] args) {

  CClass x = new CClass();

    }
} 

Output:

A constructor
B constructor
CClass constructor

  
This was an example of inheritance constructors of classes in Java.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron 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
Inline Feedbacks
View all comments
Back to top button