Login
Your Email
Pasword
Home
Write
Trending
History
Liked
Dashboard

What is Constructor Overloading in Java and When do we need it?

We can overload constructors in java and is also called based upon the parameters specified when new is executed.

Do you have similar website/ Product?
Show in this page just for only $2 (for a month)
Create an Ad
0/60
0/180
When we need to initialize an object it can be done using constructor overloading.E.g The Thread class has 8 types of constructors. If we do not want to specify anything about a thread then we can simply use default constructor of Thread class.
 If we need to specify thread name  then we cancall the parameterized constructor of Thread class with a String args .
E.g:
Thread t= new Thread (" MyThread "); 
Class for constructor overloading:
class Sample
{
 double width, height,depth; 
 Sample(double w, double h, double d)
 {
 width = w; height = h; depth = d;
 }
Sample()
 {
 width = height = depth = 0;
 } 
 Sample(double len)
 {
 width = height = depth = len;
 }
double volume()
 {
 return width * height * depth;
 }
 }
  { public static void main(String args[])
 { 
 Sample mysample1 = new Sample(10, 20, 15);
Sample mysample2 = new Sample();
 Sample mysample3 = new Sample(7);
 double vol; 
 vol = mysample1.volume();
 System.out.println(" Volume of mysample1 is " + vol); 
vol = mysample2.volume();
 System.out.println(" Volume of mysample2 is " + vol); 
 vol = mysample3.volume();
 System.out.println(" Volume of mysample3 is " + vol);
 }
 }
Use this() in constructor overloading
this() can be used during constructor overloading to call default constructor implicitly from parameterized constructor.
class Sample
 {
 double width, height, depth;
 int sampleNo; 
 Sample(double w, double h, double d, int num)
 {
 width = w;
 height = h;
 depth = d;
 sampleNo = num;
 }
Sample()
 { 
 width = height = depth = 0;
 } 
Sample(int num)
 { c
 this();
 sampleNo = num;
 }
 public static void main(String[] args)
 {
 Sample sample1 = new Sample(1);
System.out.println(box1.width);
 }
 }


Note these points while calling a constructor:
The constructor calling should be the first statement in the constructor body in Java.
If any parameterized constructor is not defined then compiler will not create default constructor.
Recursive constructor calling is not valid in java.
CONTINUE READING
Constructor Overloading
Java
Constructor Overloading in Java
Ayesha
Tech writer at newsandstory