Java – Constructor overloading with example

In earlier articles we have seen constructor and method overloading in Java in depth. Now let us mix those 2 concepts and explore constructor overloading in detail

This article will describe why constructor overloading is required and different ways to overload constructor in Java

1. Constructor Overloading :

  • Constructor overloading is a technique which allows having more than one constructor in same class
  • Of course, name of all overloaded constructor is same as that of class name and it is must but they all differs only by number of input parameters or their data types or sequence of input parameters

1.1 Different ways to overload constructor in Java, by changing

  • Number of input parameters
  • Data-type of input parameters
  • Order/sequence of input parameters, if they are of different data-types

2. Constructor Signature

Constructor signature consists of

  • Name of the constructor which should be same as that of class name
  • number of input parameters
  • their data types
  • access modifiers like private, default, protected or public
  • Note:- Access modifiers are not valid to consider in constructor overloading concept and in fact compiler throws exception if we overload constructor just by changing access modifiers keeping other things in constructor signature same

Q) Why constructor overloading is required in Java ?

  • Constructor provides a way to create objects implicitly of any class using ‘new’ keyword
  • So, overloaded constructor serves many ways to create distinct objects using different types of data of same class
  • One classical example to discuss about constructor overloading is ‘StringBuffer’ class from ‘java.lang’ package
  • StringBuffer class has four overloaded constructors
  • As highlighted in the below screen capture, StringBuffer(String str) is one of the parametrized constructor which has a initial capacity of 16 plus length of the String supplied
  • We can use this constructor if we have initial string value to supply
  • Or else, if we don’t have any idea about initial String to specify then simply use 1st overloaded constructor which has no argument (default constructor)
1_Java_Constructor_Overloading_StringBuffer_example

2.1 Things to remember about constructor overloading (constructor signature) :

Compiler checks 3 things when we overload constructor

  1. constructor-name (should be same as that of class name)
  2. number of input parameters and
  3. data-type of input parameters

2.2 Other things related to Constructor Overloading :

  • Combination of number of input parameters & their data-type has to be different for successful compilation
  • Or else compiler throws duplicate error
  • Error: Duplicate method Class_Name(input parameters) in type ClassName
2_Java_Constructor_Overloading_duplicate_constructor_error
  • Note: If name of the constructor differs and doesn’t have any return type then compiler threat this as method and throws compile time error
  • Error: Return type for the method is missing
3_Java_Constructor_Overloading_return_type_missing_error
  • Reason: When constructor’s name doesn’t matches with the class name then in that case compiler considers it has method and finds no return type hence throws above seen ‘return type missing’ error

3. Examples on Constructor-Overloading:

3.1 Constructor-Overloading based on number of input-parameters

  • Overloaded constructors differs by number of input parameters with
  • 1st being the default constructor and
  • 2nd is 2-arguments parametrized constructor

Employee.java

package in.bench.resources.constructor.example;

public class Employee {

	// member variables
	int employeeId;
	String employeeName;

	// default constructor
	Employee() {
		System.out.println("Employee class >> Inside default constructor");
		this.employeeId = 000;
		this.employeeName = "Employee 0";
	}

	// parametrized constructor
	Employee(int id, String name) {
		System.out.println("Employee class >> Inside parametrized constructor");
		this.employeeId = id;
		this.employeeName = name;

	}

	// display() method
	void displayEmployeeInfo() {
		System.out.println("Employee details\nId: " + employeeId + "\t Name: " + employeeName + "\n");
	}

	// main() method - entry point to JVM
	public static void main(String args[]) {
		Employee emp0 = new Employee();
		emp0.displayEmployeeInfo();

		Employee emp1 = new Employee(19, "Rahul Dravid");
		emp1.displayEmployeeInfo();
	}
}

Output:

Employee class >> Inside default constructor
Employee details
Id: 0	 Name: Employee 0

Employee class >> Inside parametrized constructor
Employee details
Id: 19	 Name: Rahul Dravid

Explanation:

In above example, there are two overloaded constructors

  • one is default constructor with no argument and assigns default values
  • whereas 2nd constructor takes 2 input arguments which assign values to instance variables employee id and employee name
  • after creating both the instances, displayEmployeeInfo() method is invoked with respective objects to print  employee details
  • which simply prints employee details such as Id and Name for this example

3.2 Constructor-Overloading based on data-types of input-parameters

  • Here, both overloaded constructor takes 2 input parameters and
  • they are String and int values
  • but their sequence along with data types is different

Employee.java

package in.bench.resources.constructor.example;

public class Employee {

	// member variables
	int employeeId;
	String employeeName;

	// parametrized constructor 1 (String, int)
	Employee(String name, int id) {
		this.employeeId = id;
		this.employeeName = name;
	}

	// parametrized constructor 2 (int, String)
	Employee(int id, String name) {
		this.employeeId = id;
		this.employeeName = name;
	}

	// display() method
	void displayEmployeeInfo() {
		System.out.println("Employee details\nId: " + employeeId 
                                                 + "\t Name: " + employeeName + "\n");
	}

	// main() method - entry point to JVM
	public static void main(String args[]) {
		Employee emp1 = new Employee("Michael Clarke", 23);
		emp1.displayEmployeeInfo();

		Employee emp2 = new Employee(19, "Rahul Dravid");
		emp2.displayEmployeeInfo();
	}
}

Output:

Employee details
Id: 23	 Name: Michael Clarke

Employee details
Id: 19	 Name: Rahul Dravid

Explanation:

In above example, both overloaded constructors have two input parameters with one is ‘String’ argument and another is ‘int’ argument

  • but their order/sequence of input parameters differs i.e.;
  • 1st constructor takes String as first argument and int as second argument
  • Whereas 2nd constructor takes int as first argument and String as second argument
  • So we can overload constructor based on their data types or say sequence of input parameters along with their data types
  • after creating both instances, displayEmployeeInfo() method is invoked to print employee details
  • which simply prints employee details such as Id and Name for this example

4. this() constructor:

  • Till now, we have seen default and parametrized constructor, but how to invoke one constructor from another constructor in same class
  • this() constructor call, allows us to invoke one constructor from another constructor in same class

Q) What is the need of this() constructor in overloading concept ?

  • See explanation below

Employee.java

package in.bench.resources.constructor.example;

public class Employee {

	// member variables
	int employeeId;
	String employeeName;
	String employeeOrg;

	// default constructor
	Employee() {
		System.out.println("Employee class >> Inside default constructor");
		this.employeeOrg = "Google Corporation Inc.";
	}

	// parametrized constructor (int, String)
	Employee(int id, String name) {

		this(); // to invoke another constructor from same class, this() constructor is used

		System.out.println("Employee class >> Inside parametrized constructor\n");

		this.employeeId = id;
		this.employeeName = name;
	}

	// display() method
	void displayEmployeeInfo() {
		System.out.println("Employee details:  \n\nOrgnaization: " + employeeOrg 
                           + "\nId: " + employeeId + "\nName: " + employeeName + "\n");
	}

	// main() method - entry point to JVM
	public static void main(String args[]) {
		Employee emp = new Employee(19, "Rahul Dravid");
		emp.displayEmployeeInfo();
	}
}

Output:

Employee class >> Inside default constructor
Employee class >> Inside parametrized constructor

Employee details:  

Orgnaization: Google Corporation Inc.
Id: 19
Name: Rahul Dravid

Explanation:

In above Employee class,

  • default constructor initializes organization name
  • so when we create object using arguments i.e.; 2-arguments parametrized constructor we neither supplied organization name nor parametrized constructor initializes explicitly
  • But this() constructor call does this job
  • this() constructor call, invokes default constructor to initialize organization name
  • And in the parametrized constructor other parameters like id and name gets initialized
  • When we invoke displayEmployeeInfo() method using created object, displays all employee detail

5. this() constructor call should be first statement :

  • Let us tweak above Employee class code with placing this() constructor call to last/middle statement of the constructor

Q) What happens ?

  • Compilation error: Constructor call must be the first statement in a constructor
  • See below screen capture for details
4_Java_Constructor_Overloading_this_constructor_error

Q) What if we want to invoke super class’s constructor?

  • Using super() constructor call, we can invoke super class’s constructor

Q) So, constructor overriding is possible?

  • Constructor doesn’t support inheritance,
  • so overriding is not possible
  • but accessing super class’s constructor is possible through super() call

In the following article, we will give a look through the this() & super() constructor under the heading Constructor chaining with example

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - Constructor chaining with example
Java - Default constructor v/s Parametrized constructor