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 extends A and has a method void function().
  • We create a new instance of InheritCosntructor and call its function() method.
  • First the constructor or superclass A is called and then the function() 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.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He 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