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 demonstrate the order of execution for constructors in inheritance.

Algorithm / Approach

  1. Create a base class Fruit with a default (no-argument) constructor.
  2. Create a derived class Apple that extends Fruit, also with a default constructor.
  3. In main, instantiate an Apple object.
  4. Observe how both the parent and child constructors are executed automatically.
Fruit.java
class Fruit {
 String name;
 Fruit(){
  name ="Apple";
 }
}
class Apple extends Fruit {
 int price;
 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

  • Constructors are NOT inherited by child classes. However, they are invoked when a child object is created.
  • In Java, the rule is strict: Parent constructors execute before Child constructors (Top-Down order).
  • When you write new Apple(), Java silently inserts a call to super() as the very first line of the Apple constructor, forcing it to jump up and initialize the Fruit portion of the object first.

Complexity

Time Complexity O(1)
Space Complexity O(1)
ADVERTISEMENT