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
, classB
that extendsA
andCClass
that extendsB
. - 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 inheritsA
‘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.