Constructor Overloading

Constructor overloading is the way through which multiple constructors can be defined within the class by changing the arguments of the signature. Let us understand this with an example:

public class Tech4Humans {
	public static void main(String args[]) {
		Example1 obj1 = new Example1(29,"Robert");
		System.out.println("object1 instance variables:");
		obj1.printVariables();
		
		Example1 obj2 = new Example1(29);
		System.out.println("object2 instance variables:");
		obj2.printVariables();
		
		Example1 obj3 = new Example1();
		System.out.println("object3 instance variables:");
		obj3.printVariables();
		
	}
}


class Example1{
	int age;
	String name;
	
	//Constructor Overloading
	Example1(int age, String name){
		//this keyword is used to access current class object which refers to class' instance variables
		this.age = age;
		this.name = name;
	}
	
	//Constructor Overloading. Removed 'name' parameter from signature 
	Example1(int age){
		this.age = age;
	}
	
	//Constructor Overloading. Removed all the parameters from signature
	Example1(){
		this.age = age;
	}
	
	void printVariables() {
		System.out.println("name = "+name);
		System.out.println("age = "+age+"\n");
	}
}

Output

object1 instance variables:
name = Robert
age = 29

object2 instance variables:
name = null
age = 29

object3 instance variables:
name = null
age = 0

In the above code we have overloaded the constructor by changing the number of parameters in signature. We can use any constructor for creation of the objects.

Constructor overloading is also used during Constructor chaining.

Leave a Comment