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:
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.