Types of Constructors in Java

Types of Constructors in Java

10 mins readComment
Esha
Esha Gupta
Associate Senior Executive
Updated on Jul 11, 2024 01:18 IST

Have you ever wondered how objects in Java are initialized? There are three types of constructors that handle this, i.e., default constructors provide automatic, no-argument initialization; parameterized constructors allow for custom initialization with specific values; and copy constructors create new objects as exact copies of existing ones, ensuring flexibility and control in object creation. Let's understand more!

A constructor in Java is a block of code similar to a method that is called when an instance (object) of a class is created. It is used to initialize the object and set up the initial state of the object by assigning values to its fields (variables).

Use of Constructor in Java
Use of Constructor in Java
Have you ever wondered how Java objects are initialized? Using constructors in Java is crucial for creating and setting up objects. Constructors allow developers to initialize object states and ensure...read more

Check out Java Courses Here!

Types of Constructors in Java

The main types of constructors in Java are:

Apart from these two main types of constructors in Java, there is another special constructor which is the copy constructor. We will talk about it in the later part of the blog!

Let's talk about each of these types in detail!

1. Default Constructor

A default constructor in Java is a no-argument constructor that is automatically provided by the Java compiler if no other constructors are defined in a class. Its main purpose is to initialize the object with default values.

Characteristics of a Default Constructor

 Let’s consider a real-life example of a Car class to illustrate the use of a default constructor. This example will show how a default constructor initializes an object with default values.

 

For Example,

Imagine we are developing a basic simulation for a car dealership system. Each car object should have some default values if no specific values are provided when creating a car object.

Car Class with a Default Constructor


 
public class Car {
// Fields of the Car class
String make;
String model;
int year;
String color;
// Default constructor
public Car() {
// Initializing fields with default values
this.make = "Unknown";
this.model = "Unknown";
this.year = 2000;
this.color = "White";
}
// Method to display car details
public void displayDetails() {
System.out.println("Make: " + make);
System.out.println("Model: " + model);
System.out.println("Year: " + year);
System.out.println("Color: " + color);
}
public static void main(String[] args) {
// Creating a car object using the default constructor
Car myCar = new Car();
// Displaying the details of the car
myCar.displayDetails();
// Output:
// Make: Unknown
// Model: Unknown
// Year: 2000
// Color: White
}
}
Copy code

Output

Make: Unknown
Model: Unknown
Year: 2000
Color: White

Output Explanation

  • The Car class has four fields: make, model, year, and color.
  • The default constructor Car() initializes the fields with default values: "Unknown" for make and model, 2000 for year, and "White" for color.
  • The displayDetails method prints out the details of the car.
  • In the main method, a Car object is created using the default constructor. The object myCar is initialized with the default values specified in the constructor.

This example demonstrates how a default constructor can be used to initialize an object with default values. In a real-life scenario, this can be particularly useful for creating placeholder objects or for providing default values when specific details are not yet available.

2. Parameterized Constructor

A parameterized constructor in Java is a constructor that takes one or more parameters. These parameters are used to initialize the fields of the object with specific values provided at the time of object creation. Parameterized constructors allow you to create objects with different initial states.

Key Features of Parameterized Constructors

Let's consider a real-life example involving a BankAccount class to illustrate the use of a parameterized constructor. This example will demonstrate how you can create bank account objects with specific initial values.

For Example,

Imagine we are developing a banking system where each bank account object should be initialized with specific values such as account number, account holder's name, and initial balance.

BankAccount Class with a Parameterized Constructor


 
public class BankAccount {
// Fields of the BankAccount class
String accountNumber;
String accountHolderName;
double balance;
// Parameterized constructor
public BankAccount(String accountNumber, String accountHolderName, double balance) {
this.accountNumber = accountNumber;
this.accountHolderName = accountHolderName;
this.balance = balance;
}
// Method to display account details
public void displayAccountDetails() {
System.out.println("Account Number: " + accountNumber);
System.out.println("Account Holder Name: " + accountHolderName);
System.out.println("Balance: Rs. " + balance);
}
public static void main(String[] args) {
// Creating bank account objects using the parameterized constructor
BankAccount account1 = new BankAccount("123456789", "Esha Gupta", 5000.00);
BankAccount account2 = new BankAccount("987654321", "Ravi Kumar", 10000.00);
// Displaying the details of the bank accounts
account1.displayAccountDetails();
// Output:
// Account Number: 123456789
// Account Holder Name: Esha Gupta
// Balance: Rs. 5000.0
account2.displayAccountDetails();
// Output:
// Account Number: 987654321
// Account Holder Name: Ravi Kumar
// Balance: Rs. 10000.0
}
}
Copy code

Output

Account Number: 123456789
Account Holder Name: Esha Gupta
Balance: Rs. 5000.0
Account Number: 987654321
Account Holder Name: Ravi Kumar
Balance: Rs. 10000.0

Output Explanation

  • The BankAccount class has three fields: accountNumber, accountHolderName, and balance.
  • The parameterized constructor BankAccount(String accountNumber, String accountHolderName, double balance) takes three arguments and initializes the fields of the BankAccount object with these values.
  • The displayAccountDetails method prints out the details of the bank account.
  • In the main method, two BankAccount objects are created using the parameterized constructor. The objects account1 and account2 are initialized with the values provided in the constructor calls.

Benefits of Parameterized Constructors

  • Allows objects to be initialized with specific values provided during their creation.
  • Enables the creation of objects with different states.
  • Simplifies the initialization process by combining it with object creation, making the code cleaner and more maintainable.

Real-Life Use Case

In a banking system, parameterized constructors can be used to create customer bank accounts with specific details provided by the customer. For example, when a customer opens a new account, the bank system can use a parameterized constructor to initialize the account with the customer's account number, name, and initial deposit amount.

This example demonstrates how parameterized constructors are used in real-life scenarios to initialize objects with specific values, ensuring that each object starts with the desired state.

Now, Let's Understand a Special Constructor, which is the "Copy Constructor"

A copy constructor in Java is a special type of constructor used to create a new object as a copy of an existing object of the same class. The copy constructor initializes the new object using the values of the fields from the existing object. This is particularly useful when you need to duplicate objects while ensuring that any modifications to the new object do not affect the original object.

Copy Constructor In Java
Copy Constructor In Java
Have you ever wondered how to create an exact duplicate of an object in Java? A copy constructor allows you to do just that by defining a constructor that takes...read more

Key Features of a Copy Constructor

Let's consider a real-life example involving a Student class to illustrate the use of a copy constructor. This example will demonstrate how you can create a new student object as a copy of an existing student object.

For Example,

Imagine we are developing a student management system where we need to duplicate student records. Each student object should have fields such as student ID, name, and grade.

Student Class with a Copy Constructor


 
public class Student {
// Fields of the Student class
String studentID;
String name;
double grade;
// Parameterized constructor
public Student(String studentID, String name, double grade) {
this.studentID = studentID;
this.name = name;
this.grade = grade;
}
// Copy constructor
public Student(Student student) {
this.studentID = student.studentID;
this.name = student.name;
this.grade = student.grade;
}
// Method to display student details
public void displayDetails() {
System.out.println("Student ID: " + studentID);
System.out.println("Name: " + name);
System.out.println("Grade: " + grade);
}
public static void main(String[] args) {
// Creating a student object using the parameterized constructor
Student originalStudent = new Student("S123", "Esha Gupta", 95.5);
// Creating a new student object using the copy constructor
Student copiedStudent = new Student(originalStudent);
// Displaying the details of both students
System.out.println("Original Student:");
originalStudent.displayDetails();
// Output:
// Student ID: S123
// Name: Esha Gupta
// Grade: 95.5
System.out.println("\nCopied Student:");
copiedStudent.displayDetails();
// Output:
// Student ID: S123
// Name: Esha Gupta
// Grade: 95.5
}
}
Copy code

Output

Original Student:
Student ID: S123
Name: Esha Gupta
Grade: 95.5
 
Copied Student:
Student ID: S123
Name: Esha Gupta
Grade: 95.5
Output Explanation
  • The Student class has three fields: studentID, name, and grade.
  • The parameterized constructor Student(String studentID, String name, double grade) initializes the fields with the provided values.
  • The copy constructor Student(Student student) initializes the new Student object using the values from the existing Student object passed as an argument.
  • The displayDetails method prints out the details of the student.
  • An originalStudent object is created using the parameterized constructor.
  • A copiedStudent object is created using the copy constructor, which copies the values from originalStudent.

This example demonstrates how copy constructors are used in real-life scenarios to duplicate objects with specific values, ensuring that each new object starts with the desired state. 

Comparison Table of Default Constructor, Parameterized Constructor and Copy Constructor

Feature

Default Constructor

Parameterized Constructor

Copy Constructor

Definition

A no-argument constructor provided by the compiler if no other constructors are defined.

A constructor that takes one or more parameters to initialize an object with specific values.

A constructor that creates a new object as a copy of an existing object of the same class.

Parameters

None

One or more parameters

One parameter of the same class type

Initialization

Initializes fields with default values (e.g., 0 for numbers, false for boolean, null for objects).

Initializes fields with specific values provided by the arguments.

Initializes fields with the values from an existing object.

Usage

Used when no specific initialization is required or to ensure objects have default values.

Used to initialize objects with specific values at the time of creation.

Used to create a new object with the same state as an existing object.

Automatically Provided

Yes, if no other constructors are defined.

No, it must be explicitly defined by the programmer.

No, it must be explicitly defined by the programmer.

Benefits

Ensures objects have default values; simple and straightforward.

Allows objects to be initialized with specific values; flexible and convenient.

Allows for easy duplication of objects; ensures new object has the same state as the original.

Common Use Cases

Placeholder objects, simple initializations.

Creating objects with specific configurations or initial states.

Cloning objects, ensuring new objects start with the same state as an existing object.

Thus, constructors are essential components in Java, playing a crucial role in object creation and initialization. Understanding the types of constructors allows developers to efficiently manage object creation and initialization, ensuring that objects are properly set up with the desired state right from the start.

Constructors in Java Explained
Constructors in Java Explained
In Java, constructors initialize newly created objects, setting their initial state. They share the same name as the class, lack a return type, and are automatically invoked upon object instantiation.Constructors...read more

Understanding Advantages of Java
Understanding Advantages of Java
Have you ever wondered why Java remains a popular choice among developers? Its platform independence allows programs to run on any system without modification, while its robust security features and...read more

Understanding Java Main Method
Understanding Java Main Method
Have you ever wondered how a Java application begins its execution? The key lies in the Java main method, public static void main(String[] args), which serves as the gateway for...read more

Benefits of OOPs in Java
Benefits of OOPs in Java
Have you ever wondered why Java is popular for building complex software systems? The secret lies in its Object-Oriented Programming (OOP) approach, which enhances modularity, promotes code reusability and simplifies...read more

Types of Inheritance in Java
Types of Inheritance in Java
Inheritance in Java is a fundamental Object-Oriented Programming (OOP) concept that allows one class to inherit fields and methods from another class. Inheritance enables code reuse and establishes a parent-child...read more

FAQs

What is a constructor in Java?

A constructor in Java is a special method that is used to initialize objects. It is called when an instance of a class is created and has the same name as the class. Constructors do not have a return type.

What are the types of constructors in Java?

The main types of constructors in Java are:

  • Default Constructor
  • Parameterized Constructor
  • Copy Constructor

What is a default constructor?

A default constructor is a no-argument constructor that is provided by the Java compiler if no other constructors are defined in the class. It initializes object fields with default values.

When is a default constructor provided by the compiler?

The compiler provides a default constructor if no constructors are explicitly defined in the class.

What is a parameterized constructor?

A parameterized constructor is a constructor that takes one or more parameters to initialize an object with specific values. It allows the creation of objects with user-defined initial states.

What is a copy constructor?

A copy constructor is a constructor that creates a new object as a copy of an existing object of the same class. It initializes the new object using the values of the fields from the existing object.

How do you define a copy constructor in Java?

A copy constructor is defined by creating a constructor that takes an object of the same class as a parameter and initializes the new object with the values from the given object. 

Can a class have more than one constructor?

Yes, a class can have multiple constructors with different parameter lists. This is known as constructor overloading, which allows the creation of objects in different ways.

What is constructor overloading?

Constructor overloading is the practice of having multiple constructors in a class with different parameter lists. This provides flexibility in object creation by allowing different ways to initialize objects.

What is the difference between a default constructor and a parameterized constructor?

A default constructor does not take any parameters and is provided by the compiler if no other constructors are defined. It initializes object fields with default values. A parameterized constructor takes one or more parameters and allows objects to be initialized with specific values provided during their creation.

About the Author
author-image
Esha Gupta
Associate Senior Executive

Hello, world! I'm Esha Gupta, your go-to Technical Content Developer focusing on Java, Data Structures and Algorithms, and Front End Development. Alongside these specialities, I have a zest for immersing myself in v... Read Full Bio