×

Order of Execution of Constructors in Java Inheritance

Constructor in Java

There are several distinctions between a method and a function object() in Java. The name of the function object()  is identical to the class name. There is no return type for a function object().  

If a function object()  isn't already declared in the application, Java will automatically build one. Whenever a class instance is formed, it is carried out.

Can not synchronize object () function, final, conceptual, static, or abstract. It is not revocable.

Java contains two different sorts of constructors.

standard function object()  

function object()  with parameters

Which is the inheritance order in Java for function object() execution?

Each class in a Java application that uses inheritance has its function, object(). As a result, the constructors begin to run after the object is initialized. It proceeds in a certain order by the class hierarchy. How things happen might vary depending on the inheritance type.

Different Java function object() execution order methods

1. order in which constructors are executed in single inheritance

OrderofExecutions1.java

The root class's function object()  is called first in single-level inheritance.

ParentClasss .java

//this program is for the inheritance in java
//importing the required packages
import java.io.*;
import java.util.*;
class ParentClasss   
{  
  // the default constructor     
    ParentClasss()  
    {  
        System.out.println("The execution of the parent class.");  
    }  
}  
  
// the child class  
class ChildClasss extends ParentClasss  
{ 
    // the default constructor  of the child class
    ChildClasss()  
    {  
        System.out.println("The child class is execued.");  
    }  
}  
  
public class OrderofExecutions1  
{  
    //mainsection of the program
    public static void main(String ar[])   
    {  
        // an object is created for the child class
        System.out.println("The order follows as:");  
        new ChildClasss();     
    }  
}  

Output

The order follows as:
The execution of the parent class.
The child class is execued.

The ParentClass function Object() is called first in the language above, followed by the ChildClass, after constructing an instance of the ChildClass.

2. The order in which constructors are executed under multilevel inherit

Every higher-class constructor is called when a new sample of the lowermost child class is generated under multidimensional inheritance.

OrderofExecutions2.java

//this program is for the inheritance in java
//importing the required packages
import java.io.*;
import java.util.*;
class Colleges   
{  
   // the default constructor     
    Colleges()  
    {  
        System.out.println("Colleges constructor is executed");  
    }  
}  
  
class Departments extends Colleges   
{  
    // the default constructor     


    Departments()  
    {  
        System.out.println("Departments constructor is executed");  
    }  
}  
  
class Students extends Departments  
{  
    // the default constructor     


    Students()  
    {  
    System.out.println("Execution of the Students Constructors");  
    }  
}  
public class OrderofExecutions2   
{  
     //main section of the program
    public static void main(String ar[])   
    {  
         // an object is created for the Students
        System.out.println("Execution sequence for constructors in multilayer inherit..");  
        new Students();    
    }  
}  

Output

Execution sequence for constructors in multilayer inherit..
Colleges constructor is executed
Departments constructor is executed
Execution of the Students Constructors

The code above creates a student's class object and calls the appropriate constructors for the colleges, departments, and students as needed.

3. Using this keyword to invoke the same class' function object()

Inheritance is not used in this situation. However, a single class may have several constructors so that this keyword can access these constructors.

OrderofExecutions3.java

//this program is for the inheritance in java
//importing the required packages
import java.io.*;
import java.util.*;
public class OrderofExecutions3    
{    
    // the default constructor of the class OrderofExecutions3
    OrderofExecutions3()    
    {    
        this("Ramu");    
        System.out.println("The default constructor is executed");    
    }    
    // constructor having the string as a parameter
    OrderofExecutions3(String string)    
    {    
        System.out.println("The parameterised constructor is executed");  
    }    
    // main section of the program    
    public static void main(String arr[])     
    {     
        //an object is created for the class 
        System.out.println("The order of the constructors execution.");  
        OrderofExecutions3 object = new OrderofExecutions3();     
    }     
}    

Output

The order of the constructors execution.
The parameterised constructor is executed
The default constructor is executed

Even though the default function Object()  is invoked during object creation, the parametric function Object()  is called first in the method given. This occurs due to the standard constructor's initial line, including the keywords.

4. Using the super keyword to invoke the superclass function Object()

The super keyword allows a child class function Object() or method to call the base class function Object()  or function.

ParentClasses.java

//this program is for the inheritance in java
//importing the required packages
import java.io.*;
import java.util.*; 
class ParentClasses   
{  
    int a1;  
    ParentClasses(int x1)    
    {  
        a1 = x1;  
    }  
}  
// the base class 
class ChildClasses extends ParentClasses      
{  
    int b1;  
    ChildClasses(int x1, int y1)   
    {  
        //the super keyword
        super(x1);  
        b1 = y1;  
    }  
    // the method for determining the values of the a and b
    void Shows()   
    {  
        System.out.println("The variable a1 value="+a1+"\n"+"The variable b1 value="+b1);  
    }  
}  
  
public class OrderofExecutions4  
{ 
    //main section of the program
    public static void main(String arr[])   
    {  
        System.out.println("The order in which the constructor is executing is:");  
        ChildClasses d1 = new ChildClasses(791, 891);  
        d1.Shows();  
    }  
}  

Output

The order in which the constructor is executing is:
The variable a1 value=791
The variable b1 value=891

Related Topics

Java String hashCode() method

Java String hashCode() method returns hash code for current String. hash code for string object is computed as s[0]*31^(n - 1) + s[1]*31^(n - 2) + ... + s[n - 1] Using int...

2 minutes read.

Recursion Program in Java

The recursion program in Java demonstrates the usage of recursion. The process by which a function/ method calls itself, again and again, is called recursion. Each recursive call is pushed...

10 minutes read.

Java Math acos() Method

The acos() method of Math class computes the trigonometric Arc Cosine (inverse of cosine ) of an angle. The value returned is between 0.0 to pi. Syntax: public static double acos(double a) Parameters: The...

1 minute read.

String Palindrome Program in Java

String Palindrome Program in Java The palindrome is a string, phrase, word, number, or other sequences of characters that can be read in both directions i.e. forward (left to right) and...

11 minutes read.

Java Extends vs Implements

Java: We known that the java is a pure object oriented programming language. Java programming language consists of many features such as portable, plat form independence, secured, robust, simple, architecture neutral,...

4 minutes read.

How to Convert long to int in Java

How to Convert long to int in Java When we assign a larger type value to a variable of smaller type, then we need to perform explicit casting for the conversion....

2 minutes read.

Java Generics Questions

Introduction We'll walk through a few real-world examples of interview questions and responses for Java generics in this article. Java 5 saw the debut of the fundamental idea of generics. Due to...

9 minutes read.

ArrayList VS Linked List

ArrayList VS Linked List Both the ArrayList and LinkedList implements the List interface, and they have some differences as well as some similarities between them. The internal working and performance of both vary significantly. Let’s...

7 minutes read.

Java FileNotFoundException

FileNotFoundException is another exception class accessible in the java.io bundle. The exemption happens when we attempt to get to that document which isn't accessible in the framework. It is a checked...

5 minutes read.

PriorityQueue in Java

PriorityQueue in Java A PriorityQueue is a member of the Java Collection Framework and is used when the values are needed to be processed based on priority. Priority queue operates similar to...

8 minutes read.

Java Xmx

This section will explain what Xmx in Java is and how to establish a Java application's maximum heap size. When we execute a Java application, it occasionally displays an error message...

3 minutes read.

Binary Search Java

Binary search is a search mechanism for key elements from the given List/Array. In Binary search, the search mechanism is followed by dividing the array into parts; hence the search...

3 minutes read.

What is new in Java 17?

Java 17 LTS is the most recent long-term support release for the Java SE platform. Under the Oracle No-Fee Terms and Conditions License, which stands for long-term support, JDK 17...

6 minutes read.

Java Import Keyword

Java's import keyword used in the code that follows the import statement, a Java class is declared. Once a Java class is declared, it is possible to use the class...

6 minutes read.

Fork Join in Java

Multithreaded processors are being introduced in new computer systems today. The operation is faster due to multicore CPUs. Therefore, it becomes essential for a programmer to leverage multithreaded processors effectively...

4 minutes read.

Java Naming Conventions

JAVA NAMING CONVENTIONS Java naming convention is a standard pattern for writing your identifier name such as class, interfaces, methods, constants, variable, etc. These patterns are not standard rules that you must...

2 minutes read.

Java StringReader Class

StreamReader Class technique enables character reading from a string. The java.io package contains this class. A string serves as a source in the character stream. While the Stream class is...

4 minutes read.

Sleeping Barber Problem in Java

The barbershop in this issue has one barber, one barber chair, and N chairs for customers in the waiting area. We may demonstrate the issue by keeping with the original...

6 minutes read.

Java File Input Stream

Java makes use of stream ideas to speed up input and output processes. All packages of input and output streams are contained in java.io.package. Stream: A stream is nothing more...

5 minutes read.

Bad Operand types for Binary Operator Java

We will discuss how to handle issues in bad operand types for binary operator &, bad operand types for binary operator &&, bad operand types for binary operator ==, and...

4 minutes read.