Java Constructor overloading Tutorial with Program - Scientech Easy

Java Constructor overloading Tutorial with Program

Constructor Overloading in Java


Java constructor overloading is another feature of Java object-oriented programming (OOPs). Constructor overloading means to define multiple constructors but with a different signature. i.e, It is a technique in Java in which a class can have more than one constructor that differ in the parameters list. The Java compiler differentiates these constructors based on the number of the parameter list and their types. 

Therefore, the signature of each constructor must be different. The signature of a constructor consists of its name and the sequence of parameter types. If two constructors in the same class have the same signature, it represents an ambiguity. In this case, Java compiler will generate an error message because the compiler will unable to differentiate which form to use. Hence, overload constructor must have different signatures. The simple form of constructor overloading in Java is shown in below figure.
Constructor overloading in java
Key point: 
1. Overloading means more than one form. It refers to use of the same thing for a different purpose.

Use of Constructor overloading in Java


Overloaded constructors are very common to use in Java programming based on needs because they provide many ways to create an object of a particular class. Constructor overloading allows initializing object with different types of data.
For example, consider an object having three instance variables in a class. If we need to assign a specific value to the second instance variable and the default values to be assigned to remaining variables. In this case, it can be done by declaring multiple constructors based on different signatures in a class.

Java Constructor overloading Example Programs


Let's see some practical example programs to understand the constructor overloading concept.
Program Source Code 1: Let's create a program where we will create three objects of class 'School' that will call three different constructors based on passing arguments.
    package constructorOverloadingPrograms; public class School { // Declare the instance Variables. String scName; int estYear; // Constructor overloading begins from here. // Create default constructor and Initialize values. If You don't initialize values then default values null and 0 will print as output provided by default constructor. School(){ scName="RSVM"; estYear=1975; } // Create one parameter constructor and set the name of parameter different from the name of the variable because we are not using this reference. School(String name){ scName=name; } // Create two parameters constructor and set the name of parameters different from the name of variables. School(String name, int year){ scName=name; estYear=year; } // Create an instance method to print output. You can also print output in const. void display(){ System.out.println(scName+ " " +estYear); } // Main method declaration. public static void main(String[] args) { // Create the first object with object reference variable sc. School sc=new School(); // Calling default constructor. // Create second object with object reference variable sc1. School sc1=new School("RSVM"); // Calling one parameterized constructor. // Create the third object with object reference variable sc2. School sc2=new School("RSVM",1975); // Calling two parameterized constructor. // Now call the method using reference variables sc, sc1 and sc2 one by one to print output. sc.display(); sc1.display(); sc2.display(); } }
    Output: RSVM 1975 RSVM 0 // Here 0 is the default value provided by one default constructor because we did not pass any value from one parameter constructor for second instance variable. RSVM 1975
In the preceding program, there are three constructors for School class. The first form does not accept any argument. The scName and estYear instance variables are initialized with "RSVM" and 1975. The second form accepts one string argument. This value is used to initialize the scName instance variable. 

The third form accepts two arguments string and int. These values are used to initialize scName and estYear instance variables. Thus, overloaded constructor can initialize an object by using different types of data.

Program source code 2: Let's create another program where an Employee class contains three constructors. Each of them will be used to initialize an object depending upon values we have.
    package constructorOverloadingPrograms; public class Employee { Employee(){ System.out.println("Employee Details:"); } Employee(String name){ System.out.println("Employee name: " +name); } Employee(String nCompany, int id){ System.out.println("Company name: " +nCompany); System.out.println("Employee id: " +id); } } public class Myclass { public static void main(String[] args) { Employee emp=new Employee(); Employee emp2=new Employee("Deep"); Employee emp3=new Employee("HCL", 12234); } }
    Output: Employee Details: Employee name: Deep Company name: HCL Employee id: 12234
The flow of execution of preceding programs is shown in the below figure.
Flow of execution of overloaded constructor in java

this Reference in Java


All instance methods or constructors accept an implicit argument called "this" which refers to the current object. The current object is the object on which the method is called and 'this' reference can be used inside any method or constructor to refer to the current object. 
Within the body of the method or constructor, 'this' reference can be used like any other object reference to access instance variables, instance methods, and constructors. 


The main situation where the 'this' reference can be used are:
1. When you set the name of the parameters different from the name of the instance variables inside the constructor, you can use 'this' reference to access the instance variables. You can use the following syntax.
Syntax:
             this.instance_variable_name=instance_variable_name;

2. When we need to pass a reference to the current object as an argument to another method.

3. When we need to call a constructor from another constructor. You can use this() syntax. The argument to this() must be matched with target constructor and this() must be the first line inside the constructor. By using this(), we can avoid the duplicate code in multiple constructors, especially when the initialization routine is complex. 

Program source code 3: Let us take an example of Student class in which constructor Student() has an argument "name" which is similar to the name of the instance variable "name". Now to assign the value of formal argument (Parameter) "name" to the instance variable "name", we must use dot(.) before the name of the instance variable.
    package constructorOverloadingPograms; public class Student { // Instance variable. String name; String schoolName; int rollNo; Student(String name, String sName){ this.name=name; // Here 'this' reference is used. schoolName=sName; } Student(String name, String sName, int rollNo){ this.name=name; // this reference. schoolName=sName; this.rollNo=rollNo; } void details(){ System.out.println(name+ " " +schoolName+ " " +rollNo); } public static void main(String[] args){ // Create object and pass the arguments. Student st=new Student("Riddhi", "DPS"); Student st1=new Student("Siddhi", "RSVM", 05); st.details(); st1.details(); } }

    Output: Riddhi DPS 0 Siddhi RSVM
Program source code 4: Let's create a program where we will use access modifier, encapsulation, constructor overloading, and this reference to make the program more interesting.
    package constructorOverloadingPrograms; public class Number { // Declare the variable as private. private int num=300; // Encapsulated code. // Declaration of Overloading constructor. public Number(){ // here you can also initialize the value of instance variable. } Number(int num){ this.num=num; } // Create getter method for private variable. public int getNum(){ return num; } // Create the public setter method for variable. public void setNum(int num){ this.num=num; // this reference used in method. } }
Create another class NumberTest.
    public class NumberTest { public static void main(String[] args) { Number n1=new Number(); // Calling with 0 argument. Number n2=new Number(); // Calling with 0 argument. Number n3=new Number(500); // Calling with 1 argument. Number n4=new Number(600); // Calling with 1 argument. n2.setNum(400); // assign new value. System.out.println(" First Number: " +n1.getNum()); System.out.println(" Second Number: " +n2.getNum()); System.out.println(" Third Number: " +n3.getNum()); System.out.println(" Fourth Number: " +n4.getNum()); } }
    Output: First Number: 300 Second Number: 400 Third Number: 500 Fourth Number: 600
If you have any problem to understand the Encapsulation concepts then you can learn Encapsulation in very easy ways and step by step. Practice all the programs of Encapsulation to clear the concepts.

Program source code 5:
    package constructorOverloadingPrograms; public class Fraction { private int num; // Numerator is encapsulated. So you cannot access directly from outside the class. private int deno; // Denominator is encapsulated. Fraction(int n, int d){ // Declaration and initialization of values of Instance variables. num=100; deno=200; } Fraction() { this(1,1); // Calling current class parameterized constructort. } // Create the getter method to read the values because we cannot read values directly from outside the class. public int getNum(){ return num; } public int getDeno(){ return deno; } }
    public class FractionTest { // Main method. public static void main(String[] args) { // Default constructor will be called after object creation. Fraction obj=new Fraction(); // Call the gettter method using object reference variable obj to read the value of variables. System.out.println(+obj.getNum()); System.out.println(+obj.getDeno()); } }
    Output: 100 200
Hope that this tutorial has covered all the important concepts related to Constructor Overloading in Java with practical example programs. I hope that you will have enjoyed this tutorial. If you practice all programs, I am assured that you will not have any problem to understand the concepts.
Thanks for reading!  
Next ➤ Constructor chaining in Java

⏪ Prev Next ⏩