class
Default constructor calls superclass constructor
In this example we shall show you how to call the superclass constructor in a default class constructor. An easy way to call a superclass constructor in a class constructor is to create a class that extends another class, as shown below:
- We have created a class
A
that has a default constructor without fields. - We have also created class
InheritConstructor
, that extendsA
and has a methodvoid function()
. - We create a new instance of
InheritCosntructor
and call itsfunction()
method. - First the constructor or superclass
A
is called and then thefunction()
method is called,
as described in the code snippet below.
package com.javacodegeeks.snippets.core; public class InheritConstructor extends A { public static void main(String[] c) { new InheritConstructor().function(); } public void function() { System.out.println("In InheritConstructor::function"); } } // This is the class that we extend. class A { A() { System.out.println("In A::<init>"); } }
Output:
In A::<init>
In InheritConstructor::function
This was an example of how to call the superclass constructor in a default class constructor in Java.