Write a Java program to demonstrate the order of superclass and subclass initialization


In this Java program, you have two classes, Base and Derived, which represent a base class and a derived (or subclass), respectively. These classes include instance blocks and constructors to demonstrate the order of execution during object instantiation. Here's an explanation of the program:

  • public class Main: This is the main class that contains the main method, which serves as the entry point of the program.
  • public static void main(String[] args): The main method is where the program execution begins.
  • Derived derived = new Derived();: In this line, an instance of the Derived class is created by invoking its constructor. This process will initialize both the Derived and Base classes due to inheritance.
  • class Base: This is the base class.
  • Base(): This is the constructor of the Base class. It prints "Base class constructor" when an object of the Base class is created.
  • class Derived extends Base: The Derived class inherits from the Base class.
  • Derived(): This is the constructor of the Derived class. It prints "Derived class constructor" when an object of the Derived class is created.
  • The program also includes instance initialization blocks using {} within both the Base and Derived classes. These blocks are executed before the constructors and are used to initialize instance variables or perform other tasks during object instantiation.

With this setup, here is the order of execution when you create an instance of the Derived class:

  • The Base class's instance block is executed first because the Derived class inherits from the Base class. It prints "Base class instance block."
  • The Base class's constructor is executed next, printing "Base class constructor."
  • The Derived class's instance block is executed after the Base class's constructor, printing "Derived class instance block."
  • Finally, the Derived class's constructor is executed, printing "Derived class constructor."

The program demonstrates the order in which instance blocks and constructors are executed when creating an object of a derived class that inherits from a base class.


Source Code

public class Main
{
	public static void main(String[] args)
	{
		Derived derived = new Derived();
	}
}
 
class Base //Base Class
{
	{
		System.out.println("Base class instance block");
	}
 
	Base()
	{
		System.out.println("Base class constructor");
	}
}
 
class Derived extends Base //Derived Class
{
	{
		System.out.println("Derived class instance block");
	}
 
	Derived()
	{
		System.out.println("Derived class constructor");
	}
}

Output

Base class instance block
Base class constructor
Derived class instance block
Derived class constructor