A constructor in Java Programming is a block of code that initializes (constructs) the state and value during object creation. It is called every time an object with the help of a new () keyword is created. Even if you haven’t specified any constructor in the code, the Java compiler calls a default constructor. The default constructor is used to assign default states and values, such as 0, null, etc., to the object. The general syntax of a constructor is:

class ClassName{

ClassName(){ //creating a constructor

}

}

Apart from initialization, a constructor in Java can also perform other tasks, such as calling a method, creating objects, and starting a thread. There is also a separate Constructor class in Java used to get a constructor’s internal information.

A constructor is syntactically similar to a method, but there are several differences between the two. Firstly, although it returns the current class instance, a constructor does not have any explicit return type. Secondly, it is invoked implicitly, whereas a method is not. However, similar to a method, there are a few rules for creating a constructor in Java.

Java constructors are unique methods that are called upon upon the creation of an object in order to initialize it. It is necessary to comprehend constructors in order to initialize objects and instantiate classes correctly. Take a Java course to become an expert in constructors and other important Java concepts.

Get access and complete hands-on experience on a plethora of software development skills in our unique Job Guarantee bootcamp. Get job-ready with HackerEarth and HIRIST by enrolling in our comprehensive Full Stack Java Developer Masters program today!

What is Java Constructor?

The Java constructor, a simple method, is used to initialize Java objects. It is automatically invoked at the time of object creation to set the object's preliminary states. Constructors in Java are created with the same name as the class; they do not return any type, not even void.

Key Points:

  • Name: It should have the same name as the class.
  • Unique Features of Constructors in Java
  • No Return Type: Unlike methods, a constructor has no return type.
  • Automatically called: The constructor is automatically invoked when an object is created using the new keyword, relieving you from the need to call it explicitly.
  • Types: There can be two types of constructors as follows:
  • Default Constructor: The compiler automatically provides this constructor if no constructors are defined. This kind of constructor initializes objects with default values.
  • Parameterized Constructor: A parameterized constructor allows objects to be initialized to specified values passed as arguments.

Example:

class Car {
    String model;
    int year;

    // Parameterized Constructor
    Car(String model, int year) {
        this.model = model;
        this.year = year;
    }

    void displayInfo() {
        System.out.println("Model: " + model + ", Year: " + year);
    }
}

public class Main {
    public static void main(String[] args) {
        // Creating an object of the Car class
        Car car1 = new Car("Toyota", 2020);
        car1.displayInfo();
    }
}

Dive Deep Into Java Core Concepts

Java Certification TrainingENROLL NOW
Dive Deep Into Java Core Concepts

How Do Constructors Work?

1. Object Creation with ‘new’ Keyword:

  • When you create a new object of a class using the ‘new’ keyword, Java allocates memory for the object and then calls the constructor to initialize it.
  • Example: Car myCar = new Car("Toyota", 2020);
    • Here, new Car("Toyota", 2020) creates a new instance of the Car class, and the constructor Car(String model, int year) is called to initialize the object's attributes.

2. Calling the Constructor:

  • The constructor is invoked automatically when an object is created.
  • The constructor's job is to set up the initial state of the object by assigning values to its fields or performing any setup steps needed.
  • The constructor has the same name as the class and doesn't return any value.

3. Default vs. Parameterized Constructors:

Default Constructor:

  • If no constructors are defined in the class, Java provides a default constructor with no parameters that initializes the object with default values.

Example:

class Car {
    String model;
    int year;
}

Car myCar = new Car(); // Uses default constructor

Parameterized Constructor:

  • You can define constructors with parameters to initialize objects with specific values.
  • Example
  • class Car {
        String model;
        int year;
    
        Car(String model, int year) {
            this.model = model;
            this.year = year;
        }
    }
    
    Car myCar = new Car("Toyota", 2020); // Uses parameterized constructor
    

4. Constructor Overloading:

  • You can define multiple constructors in Java in a class with different parameter lists. This is known as constructor overloading.
  • The appropriate constructor is called based on the arguments passed during object creation.
  • Example
  • class Car {
        String model;
        int year;
    
        // Default constructor
        Car() {
            this.model = "Unknown";
            this.year = 0;
        }
    
        // Parameterized constructor
        Car(String model, int year) {
            this.model = model;
            this.year = year;
        }
    }
    
    Car car1 = new Car(); // Calls default constructor
    Car car2 = new Car("Toyota", 2020); // Calls parameterized constructor
    

5. Constructor Chaining:

  • You can call one constructor in Java from another within the same class using this(). This is known as constructor chaining.
  • It helps in reducing code duplication and managing initialization in a controlled manner.
  • Example
  • class Car {
        String model;
        int year;
    
        Car() {
            this("Unknown", 0); // Calls the parameterized constructor
        }
    
        Car(String model, int year) {
            this.model = model;
            this.year = year;
        }
    }
    
    Car car1 = new Car(); // Calls default constructor which in turn calls the parameterized constructor
    

6. Super Constructor Call:

  • If a class is a subclass, its constructor can call the constructor of the superclass using super().
  • This ensures that the superclass's part of the object is initialized properly.
  • Example:
  • class Vehicle {
        String type;
    
        Vehicle(String type) {
            this.type = type;
        }
    }
    
    class Car extends Vehicle {
        String model;
        int year;
    
        Car(String model, int year) {
            super("Car"); // Calls superclass constructor
            this.model = model;
            this.year = year;
        }
    }
    
    Car car = new Car("Toyota", 2020); // Initializes both Vehicle and Car parts
    
Become job-ready and get complete job assistance by opting for the decade's hottest career option. Score your dream job in no time by enrolling in our Full Stack Java Developer Job Guarantee Program Today!

Key Features of Constructors

The following are the major characteristics and features of constructors in Java: A constructor is a special-natured method. The most significant feature is that the name of the constructor in Java is always the same as that of the class name to which it belongs. This is an identifying feature that categorizes the constructor from other methods. 

1. Same Class Name

Constructors have to be the same as the class name, which it is defined within. 

2. No Return Type

Constructors don't have a return type, and they don't even return void. They don't return any value at all. They are meant to initialize objects.

3. Automatic Invocation

The constructor is automatically invoked when an object is created with the new keyword. A user does not need to invoke the constructor explicitly.

4. Initialization of Objects

The primary purpose of a constructor is to initialize the newly created object. This contains the attribute values of an object or any setup that would be essential to do in that object.

5. Default Constructor

If our class does not have a constructor, Java provides a default constructor. A default constructor initializes the attributes to their default values (null for objects, 0 for integers).

6. Parameterized Constructors

Constructors can be declared using parameters, whereby objects can be initialized with specific values during construction. This type of constructor in Java is known as the parameterized constructor.

7. Constructor Overloading

A class can define different constructors with varying parameter lists. Another feature of constructors called constructor overloading supplies you with other ways of creating objects based on which parameters come.

8. Constructor Chaining

One constructor can call another constructor present in the same class by using this() keyword. This process is known as constructor chaining, and it avoids code redundancy and memory wastage at runtime by being very efficient in the initialization process.

9. Super Constructor Call:

In the subclass, the constructor calls the superclass constructor using the super() keyword. This determines that the superclass fields and resources are initialized, which prioritizes the subclass level of initialization.

10. Cannot be Inherited:

Subclasses do not inherit constructors in Java. Each class should define its constructors, but a subclass can use the superclass constructor using super().

11. Cannot Be Abstract, Static, or Final:

Constructors can't be abstract, static, or final. Since they are used to create objects in a class, they are compared to other keywords that don't use constructors.

12. Access Modifiers:

Constructors can have various access modifiers, such as public, protected, private, or no modifier. The level of access a constructor provides specifies where and how a class can be instantiated.

Take the Leap and Master Java Development

Java Certification TrainingENROLL NOW
Take the Leap and Master Java Development

What Are the Rules for Creating Constructors in Java?

There are a total of three rules defined for creating a constructor.

  1. The constructor’s and class’s name must be identical
  2. You cannot define an explicit value to a constructor
  3. A constructor cannot be any of these: static, synchronized, abstract, or final

One thing to note here is that you can have a public, private, or protected constructor in Java by using access modifiers that control object creation.

Types of Java Constructors

Depending on the provided parameters, there are four types of constructors in , which are:

1. No-arg Constructors

As the name gives it out, no-arg constructors do not have any arguments (parameters). If you initialize multiple objects with a no-arg constructor, all the objects’ values will be the same. Syntax of a no-arg constructor in Java is:

ClassName(){}

Let’s consider the following example for a better understanding of a no-arg constructor.

No-arg constructor example

The following example creates a no-arg constructor for the Apple class, which will be invoked during object creation.

/public-class-apple

The default constructor that the Java compiler call is also a type of no-arg constructor as it does not have any parameters. Let’s consider the following example to understand how a default constructor works.

Default constructor example

public-class2

Since you have not created any constructor in the above example, the Java compiler calls the default one. This initializes the objects with default values, and the same is displayed in the output.

2. Parameterized Constructors

Unlike no-arg constructors, parameterized constructors can accept parameters. You can make the constructor accept any number of parameters. You can use this type of constructor to assign different values to objects during creation. Here’s an example to demonstrate the functioning of a parameterized constructor in Java.

Parameterized constructor example

The following example creates a parameterized constructor with two parameters for the Car class.

public-class3

3. Copy Constructor

A copy constructor in Java is defined as a constructor used to create a new object by copying values from an existing object of the same class. This provides you with a level of control, as it's quite useful when you want to obtain a duplicate of an object with identical properties so that changes made in the newly created one will not affect the original one. Even though Java does not support any well-defined copy constructor, it can still be implemented manually.

Example:

class Car {
    String model;
    int year;

    // Parameterized constructor
    Car(String model, int year) {
        this.model = model;
        this.year = year;
    }

    // Copy constructor
    Car(Car car) {
        this.model = car.model;
        this.year = car.year;
    }

    void displayInfo() {
        System.out.println("Model: " + model + ", Year: " + year);
    }
}

public class Main {
    public static void main(String[] args) {
        Car car1 = new Car("Toyota", 2020);  // Original object
        Car car2 = new Car(car1);  // Copy constructor

        car2.displayInfo();  // Displays: Model: Toyota, Year: 2020
    }
}

4. Static Block

A static block constructor in Java is a piece of code that gets executed once the class is loaded into memory before creating any objects. It is usually used to initialize static variables or perform setup tasks only once for the class. No matter how many instances of the class are created, the execution of the static block takes place only once.

Example:

class Car {
    static String manufacturer;
    static int totalCars;

    // Static block
    static {
        manufacturer = "Toyota";
        totalCars = 0;
        System.out.println("Static block executed. Manufacturer: " + manufacturer);
    }

    Car() {
        totalCars++;
    }

    static void displayTotalCars() {
        System.out.println("Total cars produced: " + totalCars);
    }
}

public class Main {
    public static void main(String[] args) {
        Car.displayTotalCars();  // Static block is executed before this line

        Car car1 = new Car();  // Static block has already run, so only constructor runs
        Car car2 = new Car();

        Car.displayTotalCars();  // Displays: Total cars produced: 2
    }
}

What Is Constructor Overloading in Java?

A constructor in Java is almost similar to a method. Hence, it can be overloaded like the latter. Constructor overloading allows you to create multiple constructors with different parameter lists. If you want to define more than one constructor and make them perform different tasks, overloading is the way to go. The Java compiler differentiates the constructors by the numbers, sequence, and data types of their parameter lists. Let’s look at an example for better understanding.

Constructor overloading example

public-class4.

Become a Full Stack Developer in Just 6 Months!

Full Stack Java DeveloperExplore Program
Become a Full Stack Developer in Just 6 Months!
>

What Is Constructor Chaining in Java?

Constructor Chaining in Java is a process where one constructor calls another constructor within the same class or from a parent class. It ensures this doesn't happen, and the initialization runs smoothly without any code redundancy. Now, there are two ways by which constructor chaining can be done: 

  1. In the Same Class: 
  • You can call another constructor present in the same class using the this() keyword.
  • This is handy when reutilizing constructor code, especially if some constructors offer default values or have fewer parameters.
  1. Between Parent and Child Classes:
  • A child class constructor can call another constructor in its parent class using the super() keyword.
  • This ensures that the parent class is correctly initialized before the child class adds fields or logic of its own.

Example of Constructor Chaining within the Same Class:

class Car {
    String model;
    int year;

    // Default constructor
    Car() {
        this("Unknown", 0);  // Calls parameterized constructor
    }

    // Parameterized constructor
    Car(String model, int year) {
        this.model = model;
        this.year = year;
    }

    void displayInfo() {
        System.out.println("Model: " + model + ", Year: " + year);
    }
}

public class Main {
    public static void main(String[] args) {
        Car car1 = new Car();  // Calls the default constructor, which chains to the parameterized constructor
        car1.displayInfo();    // Displays: Model: Unknown, Year: 0

        Car car2 = new Car("Toyota", 2020);  // Directly calls the parameterized constructor
        car2.displayInfo();    // Displays: Model: Toyota, Year: 2020
    }
}

Key Points:

  • Constructor chaining helps to reduce code duplication.
  • It ensures a clean and manageable initialization process.
  • this() is used for chaining within the same class.
  • super() is used for chaining between parent and child classes.

How to Copy Values Without a Constructor in Java?

There is no copy constructor in Java. However, you can still copy values from one object to another by using a constructor. Here’s an example to copy values of an object using a constructor.

Copying values with the use of a constructor example

cart

There are also a few other ways to copy values without using a constructor in Java, which are:

  • Assigning values from one object to another
  • By using the clone() method

Let’s consider an example for copying values in Java by merely assigning values from one object into another.

Copying values without constructor example

The following example copies values of one object to another object without creating a constructor.

cart2

Become job-ready and get complete job assistance by opting for the decade's hottest career option. Score your dream job in no time by enrolling in our Full Stack Java Developer Job Guarantee Program Today!

Summing It Up

Java is one of the most popular and in-demand programming languages across the globe. Hence, if you want to pursue a career in software development, it is vital to learn and understand concepts such as constructors in Java. You can refer to our Java Tutorials playlist for learning more Java concepts. You can also opt for our Java Certification Training Course to get hands-on experience and lifetime access to our self-paced learning resources. to get hands-on experience and lifetime access to our self-paced learning resources.

This advanced Java Certification Training  will guide you through the concepts of Java from introductory techniques to advanced programming skills. This Java course will also provide you with the knowledge of Core Java 8, operators, arrays, loops, methods, and constructors while giving you hands-on experience in JDBC and JUnit framework.

FAQs

1. What is the purpose of the “this” keyword in constructors?

The 'this' keyword in constructors in Java refers to the current object instance. It may be used to access instance variables from the class itself; the more common reason for its use, however, is when the parameter names used are the same as the instance variable names. Also, one can call another constructor in the same class with 'this()', which enables constructor chaining.

2. How does a constructor in Java differ from a method?

A constructor differs from a method in several ways:

  • Name: A constructor has the same name as the class, while methods can have any name.
  • Return Type: Constructors do not have a return type, not even void, whereas methods must have a return type.
  • Purpose: Constructors are used to initialize objects, while methods are used to define the behavior of objects.
  • Invocation: Constructors are automatically called when an object is created, while methods need to be called explicitly.

3. Can a constructor call another constructor of the same class?

Yes, a constructor can call another constructor of the same class using the this() keyword. This is known as constructor chaining and helps in reusing code within multiple constructors.

4. Can you overload constructors in Java?

Yes, constructor overloading is possible in Java. It allows multiple constructors  with different parameter lists in the same class.

5. What happens if you don’t define a constructor in a class?

If you don’t define any constructor in a class, Java automatically provides a default constructor. This default constructor is a no-argument constructor that initializes the object with default values (e.g., 0 for integers, null for objects).

6. Can a constructor be private in Java?

Yes, Java does support private constructors. Private constructors are used when you want to manage the creation of objects from a class more precisely, like in a Singleton design pattern where you want instances of that class to be restricted only to one.

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 16 Dec, 2024

6 Months$ 8,000
Automation Test Engineer Masters Program

Cohort Starts: 27 Nov, 2024

8 months$ 1,499
Full Stack Java Developer Masters Program

Cohort Starts: 18 Dec, 2024

7 months$ 1,449
Full Stack (MERN Stack) Developer Masters Program

Cohort Starts: 8 Jan, 2025

6 Months$ 1,449