×

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 isEmpty() method

Java String isEmpty() method checks whether current String is empty or not. Syntax: public boolean isEmpty() Returns It returns true, if length of String is 0 otherwise false. Java String isEmpty() method example 1    ...

1 minute read.

Difference between String, StringBuffer and StringBuilder in java

What is a string in Java? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Java Tutorial

What is Java? Java is an object-oriented, robust, secured and platform-independent programming language. With the help of Java Programming, we can develop console, window, web, enterprise and mobile applications. Java language was...

22 minutes read.

Java 8 filters list

A stream with the components of this stream that match the given predicate is provided by the streaming filter (Predicate predicate). This process is step-by-step. Because these operations are always...

4 minutes read.

How to Convert String to Date in Java

How to Convert String to Date in java You can convert String to Date in Java by using the parse() method. There are two classes which have parse() method namely, DateFormat and SimpleDateFormat classes....

2 minutes read.

Callable Statement in Java

The Callable statement in Java is used to call the functions and Stored procedures. Example: If we want to know about the age of a person based on their date of birth,...

3 minutes read.

Untouchable Number in Java

If a number N cannot be divided properly by any positive number, it is said to be an untouchable number. Additionally known as nonaliquot numbers. The sequence is A005114 from...

3 minutes read.

How to check valid date in Java?

Every time we get data for any application, we must first ensure that it is accurate before continuing with any further processing. We might have to confirm the following while dealing...

4 minutes read.

Java vs JavaScript

Java Vs JavaScript Java and JavaScript, both play an important role in the field of Computer Technology. Most people think JavaScript is a part of Java. But it is not entirely...

4 minutes read.

Difference between String and Char Array in Java

We are heading to examine some significant differences between String and Character arrays. Both char arrays and String hold the series of characters and are utilised as a cluster of...

3 minutes read.

For Loop Program in Java

For Loop Program in Java The for-loop program in Java is written when we want a particular set of statements to be executed repeatedly until the given criteria/ condition is met....

8 minutes read.

Java Class Methods

Methods called on a class rather than a specific object instance are known as class methods. The static modifier guarantees uniform implementation across all instances of the class. Syntax public class NameOfClass...

3 minutes read.

How to Convert Decimal to Hexadecimal in Java

How to Convert Decimal to Hexadecimal in Java The hexadecimal number uses 16 values to represent a number. Numbers from 0 to 9 represented by digits and the numbers from 10...

3 minutes read.

Java Map Generic

Java arrays maintain an ordered collection of things, and the index can be used to access the data (an integer). Unlike HashMap, which stores data as a Key/Value pair. We...

3 minutes read.

Hidden classes in Java

There specifically are some APIs available in the market that generally is harmful to be used in our programs specifically literally, and until JDK 15, there, for all intents and...

4 minutes read.

Minimum Number of Platforms Required for a Railway Station

The train station problem is one of the most significant problems typically posed in the programming round interview to gauge a candidate's aptitude for logic and problem-solving. Problem of Railway Station The...

6 minutes read.

Balanced Parentheses in Java

One of the frequent programming issues, commonly referred to as the Balanced brackets issue, is the problem with the balanced parenthesis. Interviewers frequently provide this task, in which we must...

5 minutes read.

How to make Java Projects

Ant and Maven are both offered by NetBeans for the development of Java applications. When using Ant, the IDE creates an Ant build script depending on the settings you select...

6 minutes read.

Java this keyword

This Keyword in Java This keyword can be used in many different ways in Java. This is a reference variable in Java that points to the active object. In Java, the...

8 minutes read.

Java Code Optimization

We encounter the idea of optimization while working on any Java application. It is essential that the code we write is not only clear and error-free but also optimized, meaning...

9 minutes read.