top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Constructor Overloading in Java

Introduction

Constructor in Java is the most widely used paradigm that is used to initialize objects of a class. The constructor and class name are the same, and the constructor is invoked with the help of the “new” keyword. 

While constructor overriding in Java is never possible, you can still overload a constructor, unlike method overriding. When an object is created with the help of the “new” keyword, the constructor is called to set initial values to the object's instance variables. So now, what is constructor overloading?

Overview

Constructor overloading in Java refers to the ability of the paradigm to define multiple instances within itself. In simpler terms, a user invokes the overloading procedure to define multiple constructors in a class with different parameter lists. Each constructor can be different in terms of type, number, and set of parameters.

By overloading constructors, the user can create objects of the same class using different initialization values or different ways of initializing the object. This provides flexibility and allows the class to handle various scenarios when creating objects.

What is Constructor Overloading in Java?

Constructor overloading in Java means defining multiple constructors in a class, each with a different parameter list. This allows you to create objects using different initialization values or different ways of initializing the object. By overloading constructors, you can provide flexibility and handle various scenarios when creating objects of a class. Now, let’s look at a constructor program in Java with output.

Constructor overloading example:

import java.util.*;
public class Student 
{
    private int rollno;
    private int marks;
    public Student() {
        rollno = 0;
        marks = 0;
    }
    public Student(int rank) {
        rollno = rank;
        marks = rank;
    }
    public Student(int idno, int ranks) {
        rollno = idno;
        marks = ranks;
    }
  }

In the above example, the class Student has three constructors:

1. The first constructor has no parameters and initializes both objects/attributes of class Student- i.e. rollno (roll number) and marks to 0.

2. The second constructor takes a single parameter side and sets both rollno and marks to that value, i.e. the rank creating an object of class Student with two similar attributes.

3. The third constructor takes two parameters idno (student’s ID number), and ranks and assigns them to rollno and marks, respectively, creating an object of class Student with two differentiable attributes.

Now, the user can create objects of the Student class using different constructors. For example:-

Student student1 = new Student();  
Student student2 = new Student(5);  
Student student3 = new Student(003, 7);    

In the example above, student1 is created using the constructor with no arguments, student2 is created using the constructor with one argument, and student3 is created using the constructor with two arguments. Each object has different dimensions based on the constructor used.

Constructor overloading allows you to create objects with different initial states or provide different ways of object initialization based on your requirements.

When Do We Need Constructor Overloading?

If the user is looking for multiple initializations for the objects of a particular class, the paradigm of constructor overloading comes in handy. Constructor overloading aids the user in creating objects with different initial states or handling various scenarios when creating objects. Here are a few scenarios where constructor overloading can be beneficial:

1. Different Initialization Options

Just like in the example above with class Student, suppose you have a class representing a rectangle, and you want to create objects with different initialization options, for example- the length and width of the rectangle. Using constructor overloading, you can now create multiple constructors with different sets of parameters to accommodate various ways of initializing the object, such as providing a side only, which would make it a square, or providing both length and width.

public class Rect {
    private int len;
    private int wid;
 public Rect (int oneside) {
        len = oneside;
        wid = oneside; 
    }
public Rect (int length, int width)
{
len = length;
wid = width;
}
Rect rect1 = new rect(25);
Rect rect2 = new Rect(10, 25);
}

2. Handling Default Values

Constructor overloading allows you to provide default values for certain parameters, making it easier to create objects without specifying all the values. This can be helpful when some parameters are optional or have sensible default values.

public class Shop {
    private String name;
    private String category;
    private int price;
    public Shop(String nm, String cgry) {
        this.name = name;
        this.category = category;
        price = 0; // Default price
    }
    public Shop(String name, String category, int price) {
        this.name = name;
        this.category = category;
        this.price = price;
    }
Shop shop1 = new Shop("Dress", "Apparel");
Shop shop2 = new Shop("Harry Potter", "Book", 300);
}

3. Convenience and Flexibility

Constructor overloading also aids the user with convenience and flexibility, allowing them to initialize objects differently. This enhances the reusability of the class and increases the efficiency of the program syntax. Constructor overloading is thus an important paradigm that handles different initialization possibilities and helps the class become more versatile.

public class Shopkeeper 
{
    private int totalsale;
    private int expenses;
    private int profit;
    public Shopkeeper (int totalsale, int expenses, int profit) {
        this.totalsale = totalsale;
        this.expenses = expenses;
        this.profit = profit;
    }
    public Shopkeeper (int totalsale, int profit) {
        this.totalsale = totalsale;
        this.profit = profit;
        this.expenses = 4000; // Default year
    }
Shopkeeper sc1 = new Shopkeeper (8000, 6000, 4000);
Shopkeeper sc2 = new Shopkeeper (5000, 1000);
}

Constructor Overloading vs. Method Overloading

Parameter

Constructor Overloading

Method Overloading

Purpose

Initialize objects

Provide different functionality or actions

Usage

Creating objects

Performing operations or providing functionality

Invocation

Automatically invoked during object creation

Explicitly called by method name and appropriate arguments

Return Type

No return type

Can have different return types

Naming

Same name as the class

Same name within the class

Parameter Consideration

Constructor parameters are used to initialize objects with different values

Method parameters are used to affect behavior or functionality of an object

Rules for Creating Constructors in Java

There are certain rules one must be mindful of while creating Constructors in Java. Although the concept allows for a huge scope of reusability in Java programming, its syntax and rules must be kept in mind. 

  • The constructor name must be the same as the class name.

  • A constructor does not have a return type. Do not write “void” too while initializing a constructor.

  • While overloading constructors allows defining multiple constructors with the same name as the class name, each constructor must have a unique parameter list.

  • While overloading, different constructors can have different access modifiers.

  • If you do not define a constructor within a particular class, the Java compiler initializes one by default. This is known as the Default Constructor. The default constructor has no parameters and initializes instance variables to their default values, such as 0 for int, false for boolean, and so on.

  • The default constructor is not generated once the user defines a constructor explicitly within the program's scope.

  • A constructor can invoke another constructor within the same class using the this() keyword.

  • When a class extends another class, the subclass constructor implicitly or explicitly invokes the superclass constructor.

Use of this() in Constructor Overloading 

The this() keyword in Java is usually the first statement after one performs constructor overloading. It is used to invoke another constructor within the same class. 

Here's an example that demonstrates the use of this() in constructor overloading:

public class Hellothis {
    private int x;
    public Hellothis () 
{
        this(0);  
    }
    public MyClass(int y) 
{
        this.x = y;
    }
}

Copy Constructor in Java 

As the name suggests, the constructor allows the user to create a new object by copying the values of another object of the same class. 

It is a special constructor creating an independent copy of an existing object. The copy constructor is essential to create a duplicate constructor without affecting the original object when needing a deep copy. 

Copying Values Without Constructor

While copy constructor is definitely a faster method to create a duplicate of objects already initialized in the class, there are other methods to perform the same function too. These do not use constructors.

1. Using Object.clone()

The Object class provides a clone() method that can be overridden and used with the Cloneable interface to perform a shallow copy of an object. 

2. Manual object initialization or setter methods

Another way to copy values from one object to another is by using object initialization or setter methods.

Benefits of Constructor Overloading in Java

Constructor overloading provides users with several benefits to enhance the flexibility and usability of the classes. Here are the key benefits of constructor overloading:

1. Multiple initialization options

Constructor overloading allows defining multiple ways to initialize objects of a class. Users can choose the appropriate constructor based on their requirements and easily create objects with different initial states within parameterized constructors in Java or otherwise.

2. Improved re-usability

Constructor overloading enhances the re-usability of the class and its syntax by allowing the creation of multiple constructors. Users can select the constructor that best matches their needs, streamlining the instantiation process, offering only relevant information, and improving efficiency. 

3. Default values and optional parameters

Constructor overloading minimizes the need for irrelevant syntax by providing default values or making parameters optional.

4. Encapsulation and flexibility

Constructor overloading supports the principle of encapsulation by allowing users to define constructors with different access modifiers (public, private, protected). This provides control over the accessibility of the constructors and further eliminates confusion by exposing only the necessary constructors to the external code, enhancing encapsulation, and ensuring proper object initialization.

Conclusion

Constructor overloading is a special paradigm in Java that provides flexibility and versatility of program syntax. It is a powerful feature that enhances the flexibility and usability of Java classes. Constructor overloading makes the code more adaptable, readable, and user-friendly by providing multiple ways to initialize objects.

FAQs

1. Can a class have multiple copy constructors in Java?

No, Java does not support multiple copy constructors. However, if necessary, a user can opt for approaches such as the clone() method or manual copying to achieve similar functionality.

2. Can a constructor be inherited in Java?

Constructors are not inherited in Java. However, the concept of the subclass constructor is similar to implicitly or explicitly invoking the superclass constructor. This is only done to initialize inherited members of the class.

3. What is the difference between constructor overloading and method overloading in Java?

Constructor overloading is the process of defining multiple constructors in a class with different parameter lists, while method overloading in Java is the process of defining multiple methods with the same name but different parameter lists within a class.

Leave a Reply

Your email address will not be published. Required fields are marked *