Constructor Overloading in Java

In this tutorial, we will be going to discuss on the Topic Constructor overloading in Java. Further, we will be looking more on what Constructor is and how it gets overloaded.

If you don’t know about the topic Constructor overloading in java then you are at the right place because we will be discussing the topic deeply.

In Java Programming language, Constructor overloading is passing Different values to Constructors. Constructors Are Some like Similar to methods. It has a special Feature That its name is the same as that of The Class Created. It is invoked as soon as the object comes into existence. By default, Java compiler provides Default Constructor.

Types of Constructors:

  1. Default Constructors: This Constructor is called When it does N have any Parameters Passed. Basically, this constructor is called when it is to provide Default values to the object.
  2. Parameterized Constructors. This Constructor is Called When There Exists parameters. Alike, this is used when different values have to be provided to the variables.
Constructor Overloading in Java

Constructor Overloading in Java Example :

class Emp2
{  
        int id;  
        String name;  
        int age;    
        Emp2(int i,String n)
        {  
        id = i;  
        name = n;  
        }  
        Emp2(int i,String n,int a)
        {  
         	id = i;  
         	name = n;  
        	age=a;  
         }  
        void display()
  {
    System.out.println(id+" "+name+" "+age);
  }  
       
        public static void main(String args[])
  {  
        Emp2 e1 = new Emp2(189,"Aman");  
        Emp2 e2 = new Emp2(457,"Anand",89);  
        e1.display();  
        e2.display();  
       }  
    }

 

Above Example Shows the implementation of the above-discussed Constructors, that is Default Parameters and Parameterized Constructors. Here, a Class called ‘Emp2’ is created and It has Variables of Employee, that is I’d, name and age.

A Constructor has been created accepting 2 values and Another constructor has been created accepting 3 values from ‘main’ block. It is so because as discussed earlier, we can supply the constructors with Different values as much we want.

After the Both Constructors created, now I define a method ‘display’ displaying the values stored in the variables.




In the ‘main’ block, we created two objects, and with the help of them, we supply different values to Different constructors.

Output for Above Code:

output of Constructor Overloading in Java

Also read:


Leave a Reply

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