Skip to main content

Constructor Overloading in Java

Constructor Overloading in Java

We will see constructor overloading with the help of an example using this() and parameterized constructor. Before we got through the source code and examples lets discuss why we need to overload a constructor:
Constructor overloading is way of having more than one constructor which does different-2 tasks. 
You must have understood the need to overloading. Lets see how to overload a constructor with the help of below example program:

Example :

public class StudentData
{
   private int stuID;
   private String stuName;
   private int stuAge;
   StudentData()
   {
       //Default constructor
       stuID = 100;
       stuName = "New Student";
       stuAge = 18;
   }
   StudentData(int num1, String str, int num2)
   {
       //Parameterized constructor
       stuID = num1;
       stuName = str;
       stuAge = num2;
   }
   //Getter and setter methods
   public int getStuID() {
       return stuID;
   }
   public void setStuID(int stuID) {
       this.stuID = stuID;
   }
   public String getStuName() {
       return stuName;
   }
   public void setStuName(String stuName) {
       this.stuName = stuName;
   }
   public int getStuAge() {
       return stuAge;
   }
   public void setStuAge(int stuAge) {
       this.stuAge = stuAge;
   }
}

class TestOverloading
{
   public static void main(String args[])
   {
       //This object creation would call the default constructor
       StudentData myobj = new StudentData();
       System.out.println("Student Name is: "+myobj.getStuName());
       System.out.println("Student Age is: "+myobj.getStuAge());
       System.out.println("Student ID is: "+myobj.getStuID());

       /*This object creation would call the parameterized
        * constructor StudentData(int, String, int)*/
       StudentData myobj2 = new StudentData(555, "Chaitanya", 25);
       System.out.println("Student Name is: "+myobj2.getStuName());
       System.out.println("Student Age is: "+myobj2.getStuAge());
       System.out.println("Student ID is: "+myobj2.getStuID()); 
  }
}
Output:
Student Name is: New Student
Student Age is: 18
Student ID is: 100
Student Name is: Chaitanya
Student Age is: 25
Student ID is: 555
  1. As you can see in the above example that while creating the instance myobj, default constructor (StudentData()) gets called however during the creating of myobj2, the arg-constructor (StudentDate(int, String, int)) being called.Since both the constructors are having different initialization code the variables value are different in each case as shown in the output of the program.

    Let’s see role of this () in constructor overloading

public class ConstOverloading
{
   private int rollNum;
   ConstOverloading()
   {
      rollNum =100;
   }
   ConstOverloading(int rnum)
   {
      this();
      /*this() is used for calling the default  
       * constructor from parameterized constructor.
       * It should always be the first statement 
       * in constructor body.
       */
      rollNum = rollNum+ rnum;
   }
   public int getRollNum() {
   return rollNum;
   }
   public void setRollNum(int rollNum) {
   this.rollNum = rollNum;
   }
}
class TestDemo{
   public static void main(String args[])
   {
       ConstOverloading obj = new ConstOverloading(12);
       System.out.println(obj.getRollNum());
    }
}
Output:
112
As you can see in the above program that we called arg-constructor during object creation (ConstOverloading obj = new ConstOverloading(12);). However since we have placed the this() statement inside it, the default constructor implicitly being called from it.
Test your skills – Guess the output of below program
 
public class ConstOverloading
{
   private int rollNum;
   ConstOverloading()
   {
      rollNum =100;
   }
   ConstOverloading(int rnum)
   {
      rollNum = rollNum+ rnum;
      this();
   }
   public int getRollNum() {
   return rollNum;
   }
   public void setRollNum(int rollNum) {
   this.rollNum = rollNum;
   }
}
class TestDemo{
   public static void main(String args[])
   {
       ConstOverloading obj = new ConstOverloading(12);
       System.out.println(obj.getRollNum());
    }
}
Output:
Exception in thread "main" java.lang.Error: Unresolved compilation 
problem:Constructor call must be the first statement in a constructor
Program caused a compilation error. Reason: this() should be the first statement inside a constructor.
Another important point to note while overloading a constructor is: When we don’t define any constructor, the compiler creates the default constructor(also known as no-arg constructor) by default during compilation however if we have defined a parameterized constructor and didn’t define a no-arg constructor then while calling no-arg constructor the program would fail as in this case compiler doesn’t create a no-arg constructor.
Lets see the above point with the example program:

public class Demo
{
   private int rollNum;
   //We are not defining a no-arg constructor here

   Demo(int rnum)
   {
      rollNum = rollNum+ rnum;
   }
   //Getter and Setter methods
}
class TestDemo{
   public static void main(String args[])
   {
      //This statement would call no-arg constructor
      Demo obj = new Demo();
   }
}
Output:
Exception in thread "main" java.lang.Error: Unresolved compilation 
problem:The constructor Demo() is undefined

Comments

Post a Comment

Popular posts from this blog

Switch Case

Syntax : Switch Case in Java Programming It is alternative to else-if ladder. Switch Case Syntax is similar to – C/C++  Switch. Switch allows you to choose a block of statements to run from a selection of code, based on the return value of an expression. The expression used in the switch statement must return an  int, a String, or an enumerated value . switch (selection) { // value case value1 : // checking value 1 statement ( s ) ; break ; // use to break switch flow if condition match case value2 : // checking value 2 statement ( s ) ; break ; . . case value_n : statement ( s ) ; break ; default : statement ( s ) ; } Different Ways of Using Switch Case : Switch Case Using Integer Case int i=3; switch (i) { case 1 : System . out . println ( "One player is playing this game." ) ; break ; case 2 : System . out . println ( "Two players are playing

Inheritance in Java

Inheritance in Java Inheritance  is one of the feature of Object-Oriented Programming (OOPs). Inheritance allows a class to use the properties and methods of another class. In other words, the derived class inherits the states and behaviors from the base class. The derived class is also called subclass and the base class is also known as super-class . The derived class can add its own additional variables and methods. These additional variable and methods differentiates the derived class from the base class. Inheritance is a  compile-time  mechanism. A super-class can have any number of subclasses . But a subclass can have only one superclass. This is because Java does not support multiple inheritance. The superclass and subclass have  “is-a”  relationship between them. Let’s have a look at the example below. Inheritance  Example Let’s consider a superclass  Vehicle . Different vehicles have different features and properties however there few of them are common to

Multilevel inheritance

Multilevel inheritance We discussed a bit about  Multilevel inheritance  in types of inheritance in java. In this tutorial we will explain multilevel inheritance with the help of   diagram  and  example program . It’s pretty clear with the diagram that in Multilevel inheritance there is a concept of grand parent class. If we take the example of above diagram then class C inherits class B and class B inherits class A which means B is a parent class of C and A is a parent class of B. So in this case class C is implicitly inheriting the properties and method of class A along with B that’s what is called multilevel inheritance. Example : In this example we have three classes –  Car, Maruti and Maruti800. We have done a setup – class Maruti extends Car and class Maurit800 extends Maurti. With the help of this Multilevel hierarchy setup our Maurti800 class is able to use the methods of both the classes (Car and Maruti). class Car { // clas