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
- Create a base class
Fruitwith a default (no-argument) constructor. - Create a derived class
Applethat extendsFruit, also with a default constructor. - In
main, instantiate anAppleobject. - 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 tosuper()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)