Java Constructor Overloading Example

Like Method Overloading in Java, we also have some thing called as Constructor Overloading.  Constructor Overloading will have more than one constructor with different parameters which can be used for different operations. Compilers will differentiate these constructors by taking into account the number of parameters. Lets now see how to overload a constructor with the below example.

class Employee
{
	int age;
	String name;
	
	//Default Constructor
	Employee()
	{
		age =100;
		name="Test1";
	}
	
	//Parameterized Constructor
	Employee(int age,String name)
	{
		this.age =age;
		this.name=name;
	}
	
	public void disp()
	{
		System.out.println("Name : "+name+" Age : "+age);
	}
	
}
public class ConstructorOverloadingExample 
{
	public static void main(String args[])
	{
		Employee e1 = new Employee();
		Employee e2 = new Employee(10,"Test2");
		
		e1.disp();
		e2.disp();
	}
}

Output

Name : Test1 Age : 100
Name : Test2 Age : 10

As you see in the above example we have created two constructors in the Employee class one with no parameter(default) and the other one with 2 parameters. The default constructor  “Employee()” will get called when e1 (new Employee()) object is created and Empoyee(int age,String name) will be called when e2 (new Employee(10,”Test2″)) object is created.

Note : One more important point to be noted is that when we don’t define any constructor, then the compiler will create a default constructor for you. But when you have defined a parameterised constructor the compiler will not create a default constructor. Lets now redefine the above code.

class Employee
{
	int age;
	String name;
	
        //Parameterized Constructor
	Employee(int age,String name)
	{
		this.age =age;
		this.name=name;
	}
	
	public void disp()
	{
		System.out.println("Name : "+name+" Age : "+age);
	}
	
}
public class ConstructorOverloadingExample 
{
	public static void main(String args[])
	{
		Employee e1 = new Employee();
		Employee e2 = new Employee(10,"Test2");
		
		e1.disp();
		e2.disp();
	}
}

On Execution it will throw exception

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	The constructor Employee() is undefined
	at com.javainterviewpoint.ConstructorOverloadingExample.main(ConstructorOverloadingExample.java:28)

As we have defined a parameterised constructor in our code, compiler will have not be able to create a default one hence it will fail when it encounters “new Exmpoyee()”.

Comments

  1. says

    Since some classes use several constructors, and some initialization is often needed in all of them, it would be useful to add to your example how one parametrized constructor can then call another constructor for the common initialization so that code doesn’t need to be duplicated

Leave a Reply

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