Write a Java program to Call a superclass constructor from sub/child class
This Java program demonstrates constructor chaining and the use of the super keyword to call a constructor from a superclass when creating an object of a subclass. In this program, there are two classes: Super and Sub, where Sub inherits from Super. Here's an explanation of the program:
- public class Constructor: This is the main class that contains the main method, the entry point of the program.
- public static void main(String[] args) : The main method is where the program execution starts. It creates an object of the Sub class, which triggers the constructors in both the Super and Sub classes due to inheritance.
- Sub obj = new Sub();: This line creates an object of the Sub class, which triggers the constructor of the Sub class and, because of the super(); statement within the Sub constructor, also triggers the constructor of the Super class. The constructors print messages indicating that they have been called.
- class Super: This is the superclass, which has a constructor.
- Super(): The constructor of the Super class prints a message, "Super class Constructor called."
- class Sub extends Super: This is the subclass, which inherits from the Super class. It also has a constructor that calls the super() constructor from the superclass using the super keyword.
- Sub(): The constructor of the Sub class starts by calling the constructor of the Super class using super(). After that, it prints its own message, "Sub class Constructor called."
This program demonstrates constructor chaining, where the constructor of a subclass (Sub) can call the constructor of its superclass (Super) using the super keyword. When an object of the subclass is created, both constructors are called in order: first, the constructor of the superclass, and then the constructor of the subclass. This behavior is due to the inheritance relationship between the two classes.
Source Code
public class Constructor
{
public static void main(String[] args)
{
Sub obj = new Sub();
}
}
class Super
{
Super()
{
System.out.println("Super class Constructor called");
}
}
class Sub extends Super
{
Sub()
{
super();
System.out.println("Sub class Constructor called");
}
}
Output
Super class Constructor called
Sub class Constructor called