Java Program to demonstrate the order of call of Constructor.
Objective
Write a Java program to invoke a parameterized parent constructor using the super() keyword.
Algorithm / Approach
- Create a base class
Fruitwith a parameterized constructor taking a stringname. - Create a derived class
Applewith a default constructor. - Inside the
Appleconstructor, explicitly callsuper("Apple")as the first statement. - Instantiate an
Appleobject in main to observe the behavior.
Fruit.java
class Fruit {
String name;
Fruit(String name){
this.name = name;
}
}
class Apple extends Fruit {
int price;
Apple() {
super("Apple");
price = 80;
}
void display() {
System.out.println("Name- "+name);
System.out.println("Price- "+price);
}
}
class Main {
public static void main(String[] a)
{
Apple p = new Apple();
p.display();
}
}
Expected Output
Name- Apple Price- 80
Explanation of the Program
- If a parent class ONLY has a parameterized constructor, Java cannot silently insert a default
super()call into the child class, resulting in a compilation error. - To fix this, the developer must explicitly call the parent's constructor using
super(arguments). - Crucially, this explicit call to
super()MUST be the absolute first statement inside the child's constructor. You cannot write any logic before it.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)
Common Mistakes
- Placing the
super()call on the second or third line of the child constructor instead of the first. - Forgetting to write
super(args)when the parent lacks a default no-argument constructor.