Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Constructors in Java
3.
Inheritance in Java
4.
Order of Execution of Constructors in Java Inheritance
4.1.
Order of Execution in Single Level Inheritance
4.2.
Order of Execution in Multi Level Inheritance
4.3.
Calling Same Class Constructor using this Keyword
4.4.
Calling Superclass Constructor using Super Keyword
5.
Best Practices When Using Constructors and Inheritance in Java
6.
Frequently Asked Questions
6.1.
What is the order of execution of constructors in Java inheritance?
6.2.
Why does the constructor of the superclass execute first?
6.3.
What happens if the superclass does not have a constructor?
6.4.
Can a subclass constructor override the constructor of its superclass?
7.
Conclusion
Last Updated: Mar 27, 2024
Medium

Order of execution of constructors in java inheritance

Author Harshita Vyas
0 upvote
Roadmap to SDE career at Amazon
Speaker
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM

Introduction

In Java, inheritance is a powerful feature that allows a subclass to inherit properties and behavior from its superclass. When a new object is made in Java, the constructors are called to initialize the object's state. The order in which the constructors are executed during inheritance can sometimes be confusing, especially when dealing with complex class hierarchies. In this article, we shall explore the order of execution of constructors in java inheritance is and how it affects the initialization process of objects.

Order of execution of constructors in java inheritance

Also read, Swap Function in Java

Constructors in Java

In Java, constructors are special methods used to initialize objects when they are created. They are called automatically when an object is created and are used to set the initial values of instance variables or perform the necessary setup tasks. Constructors, by default, have the same name as the class they belong to and do not have a return type, not even void.

Here is an example of a simple constructor:

Code:

public class Employee
{
	// The fields of the class
	private String name;
	private int ID;


	Employee(String name, int ID) //This is constructor of the class
	{
		this.name = name;
		this.ID = ID;
		System.out.println(“Name of the Employee is ” + this.name + “ and ID is ” + this.ID);
	}
}

public class Main
{
	public static void main(String[] args) 
     {
		Employee Jack = new Employee(“Jack”, 21111);
     }

}

 

Output:

Name of the Employee is Jack and ID is 21111

 

Note: Please note that in Java you need to make separate file for the class. Here we will have two files, Employee.java and Main.java. For compiling, we compile Main.java to get the results. This applies for the examples in this article.

In this example, we have defined a constructor for the ‘Employee’ class that takes two parameters: ‘name’ and ‘ID’. Inside the constructor, we use the ‘this’ keyword to refer to the instance variables of the class and assign the parameter values to them.

Constructors can also be overloaded, which means that a class can have more than one (multiple) constructor with different parameter lists. Here's an example of an overloaded constructor:

Code:

public class Employee
{
	public:
		String name;
		int ID;

	Employee(String name)
	{
		this.name = name;
		this.ID = 0;
	}

	Employee(String name, int ID)
	{
		this.name = name;
		this.ID = ID;
	}
}

 

In this example, we have two constructors of the class ‘Employee’, one that takes only a ‘name’ parameter and sets the ‘ID’ to 0 by default, and another that takes both ‘name’ and ‘ID’ parameters.

It's important to note that if a class does not define any constructors, a default constructor with no arguments is provided automatically by the compiler.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Inheritance in Java

Inheritance is an important concept in object-oriented programming (OOP) that enables a class to inherit properties and methods from another class. This makes the code more reusable. In Java, inheritance is achieved through the use of the "extends" keyword.

The class that inherits the properties from another class is known as subclass or the derived class, and the class that is being inherited from is called the superclass or base class. The subclass can access all the public and protected properties and methods of the superclass. The private members of the superclass are not inherited by the subclass.

Inheritance in Java

Here's an example of inheritance in Java:

Code:

class Vehicle
{
	//Method of the class
	public void run() 
	{
		System.out.println("The vehicle is running.");
	}
}

class Car extends Vehicle  //subclass of vehicle class
{
	public void State() 
	{
		System.out.println("The car is parked in the garage.");
	}
}

public class Main
{
	public static void main(String args[]) 
	{
		Car myCar = new Car();
		myCar.State();
		myCar.run();
	}
}

 

Output:

The car is parked in the garage.
The vehicle is running.

 

Explanation:

In this example, the ‘Vehicle’ class is the superclass, and the ‘Car’ class is the subclass. The ‘Car’ class inherits the ‘run()’ method from the ‘Vehicle’ class and defines its own ‘State()’ method.

When the ‘main’ method is executed, a new instance of the ‘Car’ class is created, and the ‘run()’ and ‘State()’ methods are called.

Also see, Duck Number in Java and Hashcode Method in Java

Order of Execution of Constructors in Java Inheritance

When an object of a class is instantiated, the constructors of its superclass and then its own constructors are executed. This is because constructors of the superclass are responsible for initializing the state of the superclass. The state of the superclass can be used by the subclass to initialize its own state. 

Order of Execution of Constructors in Java Inheritance

Let us look at the examples to illustrate the order of execution of constructors in java inheritance:

Order of Execution in Single Level Inheritance

In single level inheritance, there is only one level of inheritance between a superclass and a subclass. The Order of execution of constructors in java inheritance in single level inheritance is as follows:

  • The constructor of the superclass is called first. If the superclass has multiple constructors, then the one with no arguments (the default constructor) is called. If the superclass does not have a default constructor, the subclass must call one of the existing constructors of the superclass explicitly using the "super" keyword by giving it the proper arguments.
     
  • Once the superclass constructor has completed its execution, the constructor of the subclass is executed. If the subclass has multiple constructors, the one that matches the arguments given at the time of object creation is called.


Know about Single Inheritance in Java in detail.

 

Order of Execution in Single Level Inheritance

Here’s an example to illustrate the order of execution of constructors in java inheritance:

Code:

class Person 
{
	//Constructor of person class
	public Person() 
	{
		System.out.println("Person constructor called.");
	}
} 

class Man extends Person //subclass of person class
{
	public Man() 
	{
		System.out.println("Man constructor called.");
	}
}

public class Main 
{
	public static void main(String args[]) 
	{
		Man myMan = new Man();
	}
}


Output:

Person constructor called.
Man constructor called.

 

Explanation:

In this example, the ‘Person’ class has a default constructor. The ‘Man’ class extends the ‘Person’ class and has its own default constructor that prints a message to the console. When the ‘main’ method is executed, a new instance of the ‘Man’ class is created. At the end, both the messages by the constructor are printed. First the message of the superclass constructor is printed and then the subclass constructor is printed.

Order of Execution in Multi Level Inheritance

In multi-level inheritance, there are multiple levels of inheritance between a superclass and a subclass. A single class has many level of parent. When an object of the subclass is created, the constructors of all the superclasses and the subclass is called. They called in a particular order to ensure proper initialization of the object.

The order of execution of constructors in java inheritance in multi-level inheritance is as follows:

  • The constructor of the topmost superclass is called first. If the topmost superclass has multiple constructors and we have not specified a particular one, then one with no arguments (the default constructor) is called. If the topmost superclass does not have a default constructor, the subclass must necessarily call one of the existing constructors of the topmost superclass explicitly using the "super" keyword by giving it the proper arguments.
     
  • Once the constructor of the topmost superclass has completed, the constructor of the immediate subclass is called (just below the topmost superclass). Again, if the immediate subclass has multiple constructors, then which one is executed depends on the program, i.e which one the program has called.
     
  • This process is repeated for each successive subclass, i.e for all the classes from which our subclass is derived, until the constructor of the subclass is executed. If the subclass has multiple constructors, the one that matches the arguments of the object creation is called.
Order of Execution in Multi Level Inheritance

An example to illustrate the Order of execution of constructors in java inheritance in multi-level inheritance in Java:

Code:

class Animal 
{
   //Constructor of Animal 
   public Animal() 
   {
    System.out.println("Animal constructor called.");
   }
}

class Mammal extends Animal //subclass of animal superclass
{
   
	public Mammal() 
	{
      System.out.println("Mammal constructor called.");
    }
}

class Dog extends Mammal 
{
   public Dog() 
	{
       System.out.println("Dog constructor called.");
    }
}

public class Main 
{
    public static void main(String args[]) 
	{
      Dog myDog = new Dog();
    }
}


Output:

Animal constructor called.
Mammal constructor called.
Dog constructor called.

In this example, the ‘Animal’ class has a default constructor that prints a message to the console. The ‘Mammal’ class extends the ‘Animal’ class and has its own default constructor that also prints a message to the console. The ‘Dog’ class extends the ‘Mammal’ class and has its own default constructor that also prints a message to the console. When the ‘main’ method is executed, a new instance of the ‘Dog’ class is created.

Calling Same Class Constructor using this Keyword

In Java, you can use the 'this' keyword to call a constructor from another constructor in the same class. This is known as constructor chaining. Constructor chaining is a concept that refers to the ability to call a constructor inside another constructor. One can use a constructor chain within the same class or even with another class. Constructor chaining can be useful when a programmer wants to avoid duplicating code in multiple constructors or when you want to set default values for variables.

An example of how to call the same class constructor using the "this" keyword:

Code:

public class Person 
{
    
    public:
    	String name;
        int age;

	public Person() 
     {
        this("Maria Allen", 0);
     }

	public Person(String name) 
     {
        this(name, 0);
     }

	public Person(String name, int age) 
     {
        this.name = name;
        this.age = age;
     }
}

 

In this example, the ‘Person’ class has three constructors. The first constructor initializes the ‘name’ and ‘age’ variables to default values using the ‘this’ keyword to call the second constructor, which takes a String parameter for the name. The second constructor, in turn, uses the ‘this’ keyword to call the third constructor, which takes both a name and an age parameter.

By using constructor chaining and the ‘this’ keyword, you can create more flexible and reusable code in your Java applications.

Calling Superclass Constructor using Super Keyword

For calling the constructor of the superclass, the "super" keyword is followed by parentheses containing all the necessary arguments for the superclass constructor. It is necessary for the call to the superclass constructor to be the first statement in the constructor of the subclass. This ensures proper initialization of the object. If the constructor of the superclass requires no arguments, the "super" keyword can be used alone.

Here is an example of how to call the constructor of a superclass using the "super" keyword in Java:

Code:

class Vehicle
{
    public String type;
    public Vehicle(String type) 
    {
        this.type = type;
    }
}

class Car extends Vehicle 
{
    int noOfWheels;
    Car(String type, int noOfWheels) 
    {
        super(type);
        this.noOfWheels = noOfWheels;
    }
}

 

In this example, the ‘Vehicle’ class has a constructor that takes a ‘type’ argument, and the ‘Car’ class extends the ‘Vehicle’ class. The ‘Car’ class has a constructor that takes both a ‘type’ and a ‘noOfWheels’ argument. The "super" keyword is used in the ‘Car’ constructor to call the constructor of the ’ class and pass the name argument to it.

Best Practices When Using Constructors and Inheritance in Java

In object-oriented programming (OOP), constructors and inheritance are two crucial ideas that let you write reusable programmes. Following are some guidelines for using constructors and inheritance in Java:

  • Use a no-argument constructor: Every class in Java has a default constructor that takes no arguments. If you don't explicitly define a constructor for your class, Java will provide a default one for you. However, it's best practice to define a no-argument constructor yourself, even if it does nothing, as this will make your code more explicit and easier to understand.
     
  • Don't use constructors to perform complex operations: Constructors should be used to initialise the state of an object, not to perform complex operations or heavy computations. If you want to perform a complex operation try to create a separate method for it.
     
  • Try using the super keyword to call the parent constructor: When you define a subclass in Java, it's important to call the parent constructor using the super keyword. This ensures that the parent class is properly initialised before the subclass. This avoids ambiguity. If you don't call the parent constructor explicitly, Java will automatically call the no-argument constructor of the parent class. This might skip some important initializations for your program. 

 

Know What is Object in OOPs here in detail.

Frequently Asked Questions

What is the order of execution of constructors in Java inheritance?

When a subclass is created, its constructors must first call a constructor in its superclass. The order of execution of constructors in Java inheritance is, firstly, the constructor of the superclass is executed then the constructor of the subclass is executed.

Why does the constructor of the superclass execute first?

The constructor of the superclass executes first because the subclass inherits all the fields and methods of the superclass, and it needs those fields and methods to be initialised properly before it can perform its own initialization.

What happens if the superclass does not have a constructor?

Every class in Java has a constructor, but if the superclass does not have an explicitly defined constructor, Java provides a default constructor with no arguments. In this case, the default constructor of the superclass will be called automatically when a subclass is created.

Can a subclass constructor override the constructor of its superclass?

No, a subclass constructor can never override the constructor of its superclass in any case. It can only call it and add the additional initialization or the code steps wherever necessary. 

Conclusion

Hope you gained enough knowledge about order of execution of constructors in Java inheritance. In conclusion, the order of execution of constructors in Java inheritance plays a crucial role in the initialization process of objects. The constructor of the superclass is always executed before the constructor of the subclass. If there are multiple levels of inheritance, the constructors of all the superclasses are executed in order, from top to bottom. 

You can consider reading related articles like ConstructorsConstructor Overloading in JavaCopy Constructor in JavaConstructor Chaining in JavaConstructor in Square Classes, Inheritance in Java, etc.

Happy reading!

 

Previous article
Constructor Overloading In Java
Next article
Constructor Chaining In Java
Live masterclass