Types of constructors in Java

Key takeaways:

  • In Java, constructors are special methods that initialize new objects, ensuring they have an initial state or specific values.

  • Java allows multiple constructors within a single class, each with different parameter lists. This is known as constructor overloading. This enables flexible object initialization.

  • Constructors have no return type, must have the same name as the class, and are called automatically when an object is created.

  • Constructors are not inherited, so each class defines its own constructors.

  • The this keyword within constructors helps differentiate instance variables from parameters, ensuring values are correctly assigned.

  • Default, parameterized, private and copy are four types of constructors in Java.

Constructors are special methods in Java used to initialize objects. When an object of a class is created, the compiler calls a constructor. The constructor’s name is always the same as the class name, and it has no return type—not even void.

In this Answer, we’ll explore the various types of constructors in Java.

Types of constructors in Java

A constructor is a block of code that functions similar to a method. When a new instance of a class is created, the constructor is called, allocating memory for the object. It’s a unique kind of method used for initializing objects, ensuring that at least one constructor is always invoked when an object is created with the new keyword.

Constructors in java
Constructors in java

There are four types of constructors in Java:

  1. Default constructor

  2. Parameterized constructor

  3. Private constructor

  4. Copy constructor

Let's examine each type in detail.

Default constructors

  • Implicit constructors: If no constructors are explicitly defined in a Java class, the compiler automatically provides a default constructor. This implicit constructor initializes the object with default values (e.g., null for reference types, 00 for numeric types, and false for booleans).

  • Non-parameterized Constructor: Often referred to as a default constructor when explicitly defined, it doesn’t take any arguments and can be implemented to execute specific initialization logic.

Let’s code a sample class with our own default (non-parameterized) constructor.

public class MyClass {
// Default constructor
public MyClass() {
// Initialization code (if any)
System.out.println("This is my default constructor");
}
public static void main(String[] args) {
// constructor is invoked while
// creating an object of MyClass
MyClass object = new MyClass();
}
}

Code explanation

  • Lines 16: We have a Java class called MyClass. This class includes our own default constructor explicitly defined in the class. The default constructor takes no arguments and doesn't have any specific initialization code in this case.

  • Line 11: When the new MyClass() statement is executed, the default constructor is called, and the message is printed, indicating that the default constructor is being invoked

Parameterized constructor

A parameterized constructor allows initializing instance variables with specific values at object creation, useful when the class has multiple instance variables that need unique values.

public class Car {
private String make;
private String model;
private int year;
// Parameterized constructor
public Car(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
System.out.println("This is my parameterized constructor and my car is "+ this.make + ", the model is "+ this.model + " and launched in year " + this.year);
}
public static void main(String[] args) {
// constructor is invoked while
// creating objects of Car
Car car1 = new Car("Toyota", "Corolla", 2022);
Car car2 = new Car("Honda", "Civic", 2023);
}
}

Code explanation

  • Line 713: The Car class has a parameterized constructor defined with three parameters: make, model, and year. When an object of the Car class is created using this constructor, the constructor is invoked with specific arguments and the instance variables make, model, and year are initialized with the provided values.

  • Lines 14–19: In the main method, two car objects are created, car1 and car2, each with different sets of values for make, model, and year.

Private constructor

Private constructors restrict the creation of objects from outside the class, commonly used in singleton patterns where only one instance of a class should exist across the application.

public class Employee {
private String name;
private int age;
private String department;
// Private constructor
private Employee(String name, int age, String department) {
this.name = name;
this.age = age;
this.department = department;
}
// Factory method to create Employee objects
public static Employee createEmployee(String name, int age, String department) {
return new Employee(name, age, department);
}
// Getter for name
public String getName() {
return name;
}
// Setter for name
public void setName(String name) {
this.name = name;
}
// Getter for age
public int getAge() {
return age;
}
// Setter for age
public void setAge(int age) {
this.age = age;
}
// Getter for department
public String getDepartment() {
return department;
}
// Setter for department
public void setDepartment(String department) {
this.department = department;
}
public static void main(String[] args) {
// Create Employee objects using the factory method
Employee employee1 = Employee.createEmployee("John Doe", 30, "HR");
Employee employee2 = Employee.createEmployee("Jane Smith", 25, "Engineering");
// Access and print employee information using getters
System.out.println("Employee 1 - Name: " + employee1.getName() + ", Age: " + employee1.getAge() + ", Department: " + employee1.getDepartment());
System.out.println("Employee 2 - Name: " + employee2.getName() + ", Age: " + employee2.getAge() + ", Department: " + employee2.getDepartment());
// Example of using setters
employee1.setName("Johnathan Doe");
employee1.setAge(31);
employee1.setDepartment("Finance");
// Print updated employee information
System.out.println("Updated Employee 1 - Name: " + employee1.getName() + ", Age: " + employee1.getAge() + ", Department: " + employee1.getDepartment());
}
}

Code explanation

  • Lines 1–4: The Employee class is defined with three private attributes: name, age, and department. These fields hold the relevant employee information and are encapsulated within the class.

  • Lines 7–11: The private constructor Employee(String name, int age, String department) initializes an Employee object with the provided name, age, and department values. Being private, it restricts object creation directly from outside the class, enforcing the use of a factory method.

  • Lines 14–16: The static factory method createEmployee(String name, int age, String department) allows for the creation of Employee instances. This method internally calls the private constructor and returns a new Employee object, providing controlled access to object construction.

  • Lines 19–26: Getter and setter methods are declared for the name attribute. getName returns the value of name, while setName(String name) allows setting or updating the value of name.

  • Lines 29–36: Getter and setter methods are declared for the age attribute. getAge returns the value of age, while setAge(int age) allows setting or updating the value of age.

  • Lines 39–46: Getter and setter methods are declared for the department attribute. getDepartment returns the value of department, while setDepartment(String department) allows setting or updating the value of department.

  • Lines 48–65: The main method serves as the entry point of the program. It demonstrates the creation of two Employee objects (employee1 and employee2) using the createEmployee factory method. It then prints their properties using getter methods. Additionally, the main method shows how to update employee1's attributes using setter methods and prints the updated information.

If you're preparing for technical interviews, understanding the object oriented programming can be a game changer. For LeetCode pattern-based problems, check out our course on Learn Object-Oriented Programming in Java.

Copy constructor

A copy constructor creates a new object by copying the state of an existing object, allowing a distinct copy with the same values without referencing the original object.

Let's create a Person class and implement a copy constructor.

public class Person {
private String name;
private int age;
// Parameterized constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Copy constructor
public Person(Person other) {
this.name = other.name;
this.age = other.age;
}
// Getters and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public static void main(String[] args) {
// Create an object using the parameterized constructor
Person person1 = new Person("John Doe", 30);
// Create another object using the copy constructor
Person person2 = new Person(person1);
// Modify person1 to demonstrate independence of objects
person1.setName("Jane Smith");
// Print the details of both persons
System.out.println("Person 1 - Name: " + person1.getName() + ", Age: " + person1.getAge());
System.out.println("Person 2 - Name: " + person2.getName() + ", Age: " + person2.getAge());
}
}

Code explanation

  • Lines 1–3: The Person class is defined with two private attributes: name and age. These fields are meant to store information about a person’s name and age and are encapsulated to restrict direct access from outside the class.

  • Lines 5–8: The parameterized constructor Person(String name, int age) initializes a Person object with the specified name and age values. It sets the private fields of the Person instance using the parameters passed during the creation of the object.

  • Lines 10–13: A copy constructor Person(Person other) is implemented. It takes another Person object as an argument and copies the name and age attributes from this object to the new instance, effectively creating a duplicate of the given Person.

  • Lines 15–19: getName and setName(String name) methods are defined to provide controlled access to the name attribute. getName returns the current value of name, whereas setName allows for modifying this value.

  • Lines 21–25: getAge and setAge(int age) methods are provided for the age attribute. getAge returns the current value of age, and setAge enables modifying the age, maintaining the encapsulation principle.

  • Lines 27–39: The main method acts as the program’s entry point. It demonstrates the creation of a Person object person1 using the parameterized constructor, and another Person object person2 using the copy constructor with person1 as its argument. The method then modifies person1's name attribute to illustrate the independence of person1 and person2. Finally, it prints the properties of both person1 and person2 to show the effect of using the copy constructor and the subsequent modification of person1.

Summarized table

Constructor

Description


Example

Default constructor


Automatically provided by Java if no other constructor is defined.


public MyClass()

Parameterized constructor

Accepts arguments to initialize object properties with specific values.


public Car(String make, String model, int year)

Private constructor


Restricts object creation from outside the class.


private Employee()

Copy constructor


Creates a new object by copying the state of another object.


public Person(Person other)

To further enhance your knowledge and skills in object oriented programming and design, we recommend the Grokking the Low Level Design Interview Using OOD Principles course, which offers interactive lessons that gives hands-on experience with coding problems and opportunities to test and refine your solutions.

Conclusion

Constructors are crucial in object-oriented programming, allowing objects to be initialized with an appropriate initial state during creation. Understanding the different types of constructors and their use cases is essential for effective object management in Java.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


How does a parameterized constructor differ from a default constructor?

A parameterized constructor allows you to set instance variables with custom values, while a default constructor initializes objects with default values.


When should we use a private constructor in Java?

Private constructors restrict object creation from outside the class, useful in singleton design patterns to ensure only one instance of a class exists.


Can a class have more than one constructor in Java?

In Java, constructor overloading allows a class to have multiple constructors with different parameter lists, enabling versatile object initialization.


Why do constructors have the same name as the class?

Constructors share the class name to signify they are part of object initialization and to distinguish them from regular methods.


Free Resources