BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Constructor Overloading in Java with examples

Last Updated: September 11, 2022 by Chaitanya Singh | Filed Under: java

Like methods, constructors can also be overloaded. In this guide we will see Constructor overloading with the help of examples. Before we proceed further let’s understand what is constructor overloading and why we do it.

Constructor overloading is a concept of having more than one constructor with different parameters list, in such a way so that each constructor performs a different task. For e.g. Vector class has 4 types of constructors. If you do not want to specify the initial capacity and capacity increment then you can simply use default constructor of Vector class like this Vector v = new Vector(); however if you need to specify the capacity and increment then you call the parameterized constructor of Vector class with two int arguments like this: Vector v= new Vector(10, 5);

constructor overloading
You must have understood the purpose of constructor overloading. Lets see how to overload a constructor with the help of following java program.

Constructor Overloading Example

Here we are creating two objects of class StudentData. One is with default constructor and another one using parameterized constructor. Both the constructors have different initialization code, similarly you can create any number of constructors with different-2 initialization codes for different-2 purposes.
StudentData.java

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;
   }

   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

Let’s understand the role of this () in constructor overloading

public class OverloadingExample2
{
   private int rollNum;
   OverloadingExample2()
   {
      rollNum =100;
   }
   OverloadingExample2(int rnum)
   {
      this();
      /*this() is used for calling the default  
       * constructor from parameterized constructor.
       * It should always be the first statement 
       * inside constructor body.
       */
      rollNum = rollNum+ rnum;
   }
   public int getRollNum() {
	  return rollNum;
   }
   public void setRollNum(int rollNum) {
	  this.rollNum = rollNum;
   }
   public static void main(String args[])
   {
	   OverloadingExample2 obj = new OverloadingExample2(12);
       System.out.println(obj.getRollNum());
    }
}

Output:

112

As you can see in the above program that we called the parameterized constructor during object creation. Since we have this() placed in parameterized constructor, the default constructor got invoked from it and initialized the variable rollNum.

Test your skills – Guess the output of the following program

public class OverloadingExample2
{
   private int rollNum;
   OverloadingExample2()
   {
      rollNum =100;
   }
   OverloadingExample2(int rnum)
   {
     
      rollNum = rollNum+ rnum;
      this();
   }
   public int getRollNum() {
      return rollNum;
   }
   public void setRollNum(int rollNum) {
      this.rollNum = rollNum;
   }
   public static void main(String args[])
   {
       OverloadingExample2 obj = new OverloadingExample2(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 gave a compilation error. Reason: this() should be the first statement inside a constructor.

Another Constructor overloading Example

Another important point to note while overloading a constructor is: When we don’t implement any constructor, the java compiler inserts the default constructor into our code during compilation, however if we implement any constructor then compiler doesn’t do it. See the example below.

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

   public static void main(String args[])
   {
      //This statement would invoke no-arg constructor
      Demo obj = new Demo();
   }
}

Output:

Exception in thread "main" java.lang.Error: Unresolved compilation 
problem:The constructor Demo() is undefined

Top Related Articles:

  1. Difference between HashMap and Hashtable
  2. Java – Default constructor with example
  3. Multilevel inheritance in java with example
  4. Check key & Value existence in Hashtable example – Java
  5. Final Keyword In Java – Final variable, Method and Class

Tags: Java-OOPs

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Comments

  1. vikashini says

    March 25, 2014 at 4:55 PM

    very useful…

    Reply
  2. jayaram says

    April 30, 2014 at 7:17 AM

    Really good example for constructor overloading.

    Thanks
    Jayaram

    Reply
  3. Suhas says

    August 18, 2014 at 2:52 PM

    Good explanation with examples. Thanks

    Reply
  4. Sudheer says

    November 27, 2014 at 9:10 AM

    This is so clear

    Reply
  5. Agus says

    April 27, 2015 at 4:09 AM

    Wow.. this is really helpful for me on my java class. Thanks so much :)

    Reply
  6. Rajesh Kumar Dash says

    June 29, 2015 at 7:54 AM

    Its on of the best website for java reference. All the concepts are so clearly explained. Uts truely value its name as Beginner’s Book. I am really thanks to the author and all the people working behind the team.No need to open 4-3 sites simultaneously. The contains are enough to build your fundamentals and to clear your doubt.
    The page is so simple and effective. Great UI and great design of the page too. I really appriciate your hard work. Keep it up.

    Reply
  7. ramya says

    December 13, 2015 at 3:51 AM

    thanks a lotttttt.
    It is very helpful your explanation for each n every concept is so good.

    Reply
  8. parvin says

    December 26, 2015 at 7:39 PM

    Hi…the explanation is very simple and useful.
    I have few questions.

    1.What if child class’s constructor is being called and it’s parent class does not a default constructor(which is expected to be called implicitly)? Will complier throw error?

    2.if child class’s default constructor is being called,where first statement is this(parameter);
    Will this call parent’s default constructor first and then will invoke parametrized constructor of current object?

    3.if in child’s default constructor which is being called first statement is super(); and second is this();
    Will this work in anyway?if yes then how?
    Or then it will throw compilation error as both the statement’s requirement is to be first statement.

    Reply
  9. anu says

    February 5, 2016 at 1:02 PM

    What’s the use of getter and setter method here while we could pass the values in object

    Reply
  10. Rana Chakraborty says

    November 3, 2016 at 7:31 AM

    This is a quite useful example, and very well explained.

    This site is very helpful for those who wants to learn JAVA.

    Best regards and good wishes !!!

    Reply
  11. Chirag H G says

    March 1, 2017 at 5:20 AM

    Hi, In the 2nd example. In the comment section, you have written ” this() is used for calling the default constructor from parameterized constructor.”

    I believe, this() is used to call no-argument constructor from parameterized constructor.

    Correct me, if i am wrong!!!!.

    This is one of the best website i found to learn java effectively. Keep up the good work!!.

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap