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:  
  

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button