Scientech Easy Java Constructor overloading Tutorial with Program | Scientech Easy

Friday, March 22, 2019

Java Constructor overloading Tutorial with Program

Constructor Overloading in Java


Before we proceed further, let's understand the concept of overloading. The main concept of overloading is "Same name, Different parameters or different signature". Thus, we can define as "Java Constructor overloading is a technique in which a class can have more than one constructor having the same name with different parameters listi.e. When a class has more than one constructor having the same name but different parameters within the same class, we can say that the constructor is overloaded. 
Key points:
1. Overloaded constructor means you have more than one constructor in your class and to compile each constructor must have a different argument list.
2. When the multiple constructors are executed after creating an object, the compiler differentiates these constructors by taking the order, number, and the types of parameters used in the list. The following figure shows the technique of constructor overloading in Java.
Java constructor overloading.
Let's see a simple example to understand the constructor overloading concept.
Program Source Code 1:
In this example program, we will create three objects of class 'School'. One with default constructor with initialization value of the instance variables, second with one parameter, and third with two parameters constructor.
    package scientecheasy; 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 const. School(){ scName="RSVM"; estYear=1975; } // Create one parameter constructor. // Here we are setting 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 const. // Create second object with object reference variable sc1. School sc1=new School("RSVM"); // Calling one parameterized const. // Create the third object with object reference variable sc2. School sc2=new School("RSVM",1975); // Calling two parameterized const. // 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 above example program, we called default and parameterized constructors using different object creation. You can create any number of constructor within a class but the concept will always be the same. 

this Reference in Java


All instance methods receive an implicit argument called 'this' which refers to the current object. The current object is the object on which the method was called and 'this' reference can be used inside any method to refer to the current object. 
In the body of the method or constructor, the 'this' reference can be used like any other object reference to access instance variables, instance methods, and constructor. 
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 or method, in this case, we can use 'this' reference to access the instance variables. You can use the following syntax:
                 this.instance_variable_name=instance_variable_name;

2. When you need to pass a reference to the current object as an argument to another method.
3. When you need to call a constructor from another constructor. You can use this() syntax. The argument to this() must match with target constructor and this() must be the first line inside the constructor. 
You can learn more details about this keyword. 
By using this(), the duplicate code can be avoided in multiple constructors, especially when the initialization routine is complex. 

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.
Program Source Code 2: 
You must follow all the above steps to make overloading.
    package scientecheasy; 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 3: 
In this program, we will use Access modifier, Encapsulation, Constructor overloading, and this reference to make the program more interesting.
    package scientecheasy; 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 and call the class Number.
    package scientecheasy; 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 4: 
    package scientecheasy; 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; } }
Now create another class and create the object of the class Fraction.
    package scientecheasy; 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 programs. We 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 ⏩