Constructor Overloading in Java
Last Updated :
16 Jun, 2023
Java supports Constructor Overloading in addition to overloading methods. In Java, overloaded constructor is called based on the parameters specified when a new is executed.
When do we need Constructor Overloading?
Sometimes there is a need of initializing an object in different ways. This can be done using constructor overloading.
For example, the Thread class has 8 types of constructors. If we do not want to specify anything about a thread then we can simply use the default constructor of the Thread class, however, if we need to specify the thread name, then we may call the parameterized constructor of the Thread class with a String args like this:
Thread t= new Thread (" MyThread ");
Let us take an example to understand the need of constructor overloading. Consider the following implementation of a class Box with only one constructor taking three arguments.
// An example class to understand need of
// constructor overloading.
class Box
{
double width, height,depth;
// constructor used when all dimensions
// specified
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
// compute and return volume
double volume()
{
return width * height * depth;
}
}
As we can see that the Box() constructor requires three parameters. This means that all declarations of Box objects must pass three arguments to the Box() constructor.
For example, the following statement is currently invalid:
Box ob = new Box();
Since Box() requires three arguments, it’s an error to call it without them. Suppose we simply wanted a box object without initial dimension, or want to initialize a cube by specifying only one value that would be used for all three dimensions. From the above implementation of the Box class, these options are not available to us. These types of problems of different ways of initializing an object can be solved by constructor overloading.
Example of Constructor Overloading
Below is the improved version of class Box with constructor overloading.
Java
class Box {
double width, height, depth;
Box( double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
Box() { width = height = depth = 0 ; }
Box( double len) { width = height = depth = len; }
double volume() { return width * height * depth; }
}
public class Test {
public static void main(String args[])
{
Box mybox1 = new Box( 10 , 20 , 15 );
Box mybox2 = new Box();
Box mycube = new Box( 7 );
double vol;
vol = mybox1.volume();
System.out.println( "Volume of mybox1 is " + vol);
vol = mybox2.volume();
System.out.println( "Volume of mybox2 is " + vol);
vol = mycube.volume();
System.out.println( "Volume of mycube is " + vol);
}
}
|
Output
Volume of mybox1 is 3000.0
Volume of mybox2 is 0.0
Volume of mycube is 343.0
Using this() in Constructor Overloading
this() reference can be used during constructor overloading to call the default constructor implicitly from the parameterized constructor.
Below is the implementation of the above method:
Java
public class Box {
double width, height, depth;
int boxNo;
Box( double w, double h, double d, int num)
{
width = w;
height = h;
depth = d;
boxNo = num;
}
Box()
{
width = height = depth = 0 ;
}
Box( int num)
{
this ();
boxNo = num;
}
public static void main(String[] args)
{
Box box1 = new Box( 1 );
System.out.println(box1.width);
}
}
|
As we can see in the above program we called Box(int num) constructor during object creation using only box number. By using this() statement inside it, the default constructor(Box()) is implicitly called from it which will initialize the dimension of Box with 0.
Note : The constructor calling should be first statement in the constructor body.
For example, the following fragment is invalid and throws compile time error.
Box(int num)
{
boxNo = num;
/* Constructor call must be the first
statement in a constructor */
this(); /*ERROR*/
}
Important points to be taken care of while doing Constructor Overloading
- Constructor calling must be the first statement of the constructor in Java.
- If we have defined any parameterized constructor, then the compiler will not create a default constructor. and vice versa if we don’t define any constructor, the compiler creates the default constructor(also known as no-arg constructor) by default during compilation
- Recursive constructor calling is invalid in Java.
FAQ in Constructor Overloading
1. Differentiate Constructors Overloading vs Method Overloading.
Answer:
Strictly speaking, constructor overloading is somewhat similar to method overloading. If we want to have different ways of initializing an object using a different number of parameters, then we must do constructor overloading as we do method overloading when we want different definitions of a method based on different parameters.
Related Topics
Similar Reads
Java Constructors
In Java, constructors play an important role in object creation. A constructor is a special block of code that is called when an object is created. Its main job is to initialize the object, to set up its internal state, or to assign default values to its attributes. This process happens automaticall
10 min read
Default constructor in Java
Like C++, Java automatically creates default constructor if there is no default or parameterized constructor written by user, and (like C++) the default constructor automatically calls parent default constructor. But unlike C++, default constructor in Java initializes member data variable to default
1 min read
Private Constructors and Singleton Classes in Java
In Java, the private constructor is a special type of constructor that cannot be accessed from outside the class. This is used in conjunction with the singleton design pattern to control the instantiation. Private ConstructorThe private constructor is used to resist other classes to create new insta
2 min read
Copy Constructor in Java
Like C++, Java also supports a copy constructor. But, unlike C++, Java doesn't create a default copy constructor if you don't write your own. A prerequisite prior to learning copy constructors is to learn about constructors in java to deeper roots. Below is an example Java program that shows a simpl
4 min read
Constructor Chaining In Java with Examples
Constructor chaining is the process of calling one constructor from another constructor with respect to current object. One of the main use of constructor chaining is to avoid duplicate codes while having multiple constructor (by means of constructor overloading) and make code more readable. Prerequ
5 min read
Why Constructors are not inherited in Java?
Constructor is a block of code that allows you to create an object of class and has same name as class with no explicit return type. Whenever a class (child class) extends another class (parent class), the sub class inherits state and behavior in the form of variables and methods from its super clas
2 min read
Constructor Overloading in Java
Java supports Constructor Overloading in addition to overloading methods. In Java, overloaded constructor is called based on the parameters specified when a new is executed. When do we need Constructor Overloading? Sometimes there is a need of initializing an object in different ways. This can be do
5 min read
Static Blocks in Java
In simpler language whenever we use a static keyword and associate it to a block then that block is referred to as a static block. Unlike C++, Java supports a special block, called a static block (also called static clause) that can be used for static initialization of a class. This code inside the
4 min read
The Initializer Block in Java
In order to perform any operations while assigning values to an instance data member, an initializer block is used. In simpler terms, the initializer block is used to declare/initialize the common part of various constructors of a class. It runs every time whenever the object is created. The initial
2 min read
Order of execution of Initialization blocks and Constructors in Java
Prerequisite : Static blocks, Initializer block, Constructor In a Java program, operations can be performed on methods, constructors and initialization blocks. Instance Initialization Blocks : IIB are used to initialize instance variables. IIBs are executed before constructors. They run each time wh
4 min read