Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to demonstrate the order of call of Constructor.

Java Code Example — Inheritance Programs

ADVERTISEMENT

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

  1. Create a base class Fruit with a parameterized constructor taking a string name.
  2. Create a derived class Apple with a default constructor.
  3. Inside the Apple constructor, explicitly call super("Apple") as the first statement.
  4. Instantiate an Apple object 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.
ADVERTISEMENT