×

Java Programs

Java Practice

Java program to call a superclass constructor from sub/child class

Learn how to call a superclass constructor from sub/child class in Java?
Submitted by Nidhi, on March 23, 2022

Problem statement

In this program, we will inherit a class into another class using the "extends" keyword. Then we will call Superclass constructor from child/subclass constructor using the 'super' keyword.

Java program to call a superclass constructor from sub/child class

The source code to call a superclass constructor from sub/child class is given below. The given program is compiled and executed successfully.

// Java program to call a superclass constructor 
// from sub/child class

class Super {
  Super() {
    System.out.println("Super class constructor called.");
  }
}

class Sub extends Super {
  Sub() {
    super();
    System.out.println("Sub class constructor called.");
  }
}

public class Main {
  public static void main(String[] args) {
    Sub obj = new Sub();
  }
}

Output

Super class constructor called.
Sub class constructor called.

Explanation

In the above program, we created 3 classes Super, Sub, and Main. The Super and Subclass contain a constructor. Here, we inherited the Superclass into Sub class using the "extends" keyword.  In the Sub Class constructor, we accessed the superclass constructor using the super keyword.

The Main class contains a method main(). The main() method is the entry point for the program, here we created the object of Subclass and called both class constructors, and printed the messages.

Java Inheritance Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.