Skip to content

Constructors in Java

1. What is a Constructor?

A constructor is a special member of a Java class that is used to initialize objects.

Important characteristics

  1. Constructor name must be the same as the class name.
  2. A constructor does not have a return type, not even void.
  3. It is automatically called when an object is created using new.
  4. Constructors are mainly used to initialize instance variables.
  5. A class can have more than one constructor.

Example

filename.java
class Student {
    int rollNo;
    String name;

    Student() {
        rollNo = 101;
        name = "Ravi";
    }

    void display() {
        System.out.println(rollNo);
        System.out.println(name);
    }

    public static void main(String[] args) {
        Student s1 = new Student();
        s1.display();
    }
}

Output

 
 
101
Ravi
 

When this statement executes:

 
 
Student s1 = new Student();
 

the constructor Student() is automatically called.

2. Default Constructor

If you do not write any constructor in a class, Java provides a default constructor automatically.

 
 
class Student {
int rollNo;
String name;
}
 

Java conceptually provides:

 
 
Student() {
}
 

Therefore:

 
 
Student s1 = new Student();
 

is valid.

The instance variables receive their default values:

 
 
rollNo = 0
name = null
 

Important point

If you write any constructor yourself, Java does not automatically provide the no-argument default constructor.

For example:

 
 
class Student {
int rollNo;
 
Student(int r) {
rollNo = r;
}
}
 

This is valid:

 
 
Student s1 = new Student(101);
 

But this is invalid:

 
 
Student s2 = new Student();
 

because no Student() constructor has been defined.

3. No-Argument Constructor

A constructor that does not accept any parameters is called a no-argument constructor.

filename.java
class Employee {
    int empNo;
    String name;

    Employee() {
        empNo = 101;
        name = "Anil";
    }
}

Creating the object:

 
 
Employee e1 = new Employee();
 

calls:

 
 
Employee()
 

4. Parameterized Constructor

A constructor that accepts parameters is called a parameterized constructor.

filename.java
class Student {
    int rollNo;
    String name;

    Student(int r, String n) {
        rollNo = r;
        name = n;
    }

    void display() {
        System.out.println(rollNo + " " + name);
    }

    public static void main(String[] args) {
        Student s1 = new Student(101, "Ravi");
        Student s2 = new Student(102, "Sita");

        s1.display();
        s2.display();
    }
}

Here:

 
 
new Student(101, “Ravi”)
 

passes 101 and "Ravi" to the constructor.


5. Constructor Overloading

Constructor overloading means defining multiple constructors in the same class with different parameter lists.

The constructors must differ in:

  • Number of parameters, or
  • Type of parameters, or
  • Order of parameters

Example

filename.java
class Student {
    int rollNo;
    String name;
    double marks;

    Student() {
        rollNo = 0;
        name = "Unknown";
        marks = 0;
    }

    Student(int r) {
        rollNo = r;
        name = "Unknown";
        marks = 0;
    }

    Student(int r, String n) {
        rollNo = r;
        name = n;
        marks = 0;
    }

    Student(int r, String n, double m) {
        rollNo = r;
        name = n;
        marks = m;
    }

    void display() {
        System.out.println(rollNo + " " + name + " " + marks);
    }

    public static void main(String[] args) {
        Student s1 = new Student();
        Student s2 = new Student(101);
        Student s3 = new Student(102, "Ravi");
        Student s4 = new Student(103, "Sita", 85.5);

        s1.display();
        s2.display();
        s3.display();
        s4.display();
    }
}

Here the class contains four overloaded constructors.

Java determines which constructor to call based on the arguments supplied with new.


6. Constructor Overloading Based on Data Type

Constructors can also be overloaded using different parameter types.

filename.java
class Demo {

    Demo(int x) {
        System.out.println("Integer constructor");
    }

    Demo(double x) {
        System.out.println("Double constructor");
    }

    Demo(String x) {
        System.out.println("String constructor");
    }

    public static void main(String[] args) {
        Demo d1 = new Demo(10);
        Demo d2 = new Demo(10.5);
        Demo d3 = new Demo("Java");
    }
}

Output:

 
 
Integer constructor
Double constructor
String constructor
 

7. Constructor Overloading Based on Order of Parameters

Parameter order can also be different.

 
filename.java
class Person {

    Person(int age, String name) {
        System.out.println("Age: " + age + ", Name: " + name);
    }

    Person(String name, int age) {
        System.out.println("Name: " + name + ", Age: " + age);
    }

    public static void main(String[] args) {
        Person p1 = new Person(25, "Ravi");
        Person p2 = new Person("Sita", 22);
    }
}

The parameter lists are different:

 
 
(int, String)
(String, int)
 

Therefore, these are valid overloaded constructors.


8. Constructor vs Method

ConstructorMethod
Same name as classCan have any valid name
No return typeMay have a return type
Automatically called when object is createdUsually called explicitly
Used mainly for initializationUsed to perform operations
Cannot be inheritedMethods can be inherited
Can be overloadedCan be overloaded
Cannot be declared staticCan be static

Example

filename.java
class Student {

    Student() {              // Constructor
        System.out.println("Constructor called");
    }

    void display() {         // Method
        System.out.println("Method called");
    }

    public static void main(String[] args) {

        Student s = new Student();

        s.display();
    }
}

9. Using this in a Constructor

When constructor parameters have the same names as instance variables, use this.

 
 
class Student {
int rollNo;
String name;
 
Student(int rollNo, String name) {
this.rollNo = rollNo;
this.name = name;
}
 
void display() {
System.out.println(rollNo + ” “ + name);
}
 
public static void main(String[] args) {
Student s = new Student(101, “Ravi”);
s.display();
}
}
 

Here:

 
 
this.rollNo
 

refers to the object’s instance variable, while:

 
 
rollNo
 

refers to the constructor parameter.


10. Constructor Chaining Using this()

One constructor can call another constructor of the same class using this().

 
 
class Student {
 
int rollNo;
String name;
 
Student() {
this(101, “Unknown”);
}
 
Student(int rollNo, String name) {
this.rollNo = rollNo;
this.name = name;
}
 
void display() {
System.out.println(rollNo + ” “ + name);
}
 
public static void main(String[] args) {
Student s1 = new Student();
s1.display();
}
}
 

Execution:

 
 
new Student()
Student()
this(101, “Unknown”)
Student(int, String)
 

Important rule

this() must be the first statement inside a constructor.


11. Calling Parent Constructor Using super()

A constructor of a child class can call the parent class constructor using super().

 
 
class Person {
 
Person() {
System.out.println(“Person constructor”);
}
}
 
class Student extends Person {
 
Student() {
super();
System.out.println(“Student constructor”);
}
 
public static void main(String[] args) {
Student s = new Student();
}
}
 

Output:

 
 
Person constructor
Student constructor
 

super() must also be the first statement of the constructor.


12. Important Rules for Constructors

Remember these points:

  • Constructor name = class name.
  • Constructor has no return type.
  • Constructors are called when objects are created.
  • Constructors can be overloaded.
  • Constructor overloading is a form of compile-time polymorphism.
  • Constructors cannot be inherited.
  • Constructors cannot be overridden.
  • A constructor can be public, protected, default/package-private, or private.
  • A constructor cannot be static.
  • A constructor cannot be abstract.
  • this() calls another constructor in the same class.
  • super() calls a constructor of the parent class.
  • this() or super() must be the first statement.

Practice Questions

A. Conceptual Questions

  1. What is a constructor in Java?
  2. Why does a constructor not have a return type?
  3. What is the difference between a constructor and a method?
  4. What happens if a class does not contain any constructor?
  5. What is a no-argument constructor?
  6. What is a parameterized constructor?
  7. What is constructor overloading?
  8. How does Java identify which overloaded constructor should be executed?
  9. Can constructors be overloaded?
  10. Can constructors be overridden?
  11. Can a constructor be declared static?
  12. What is the purpose of this() inside a constructor?
  13. What is the purpose of super() inside a constructor?
  14. Why must this() be the first statement in a constructor?
  15. What happens when a programmer defines a parameterized constructor but tries to create an object using new ClassName()?

B. Predict the Output

Question 1

 
 
class Test {
Test() {
System.out.println(“A”);
}
 
Test(int x) {
System.out.println(“B”);
}
 
public static void main(String[] args) {
Test t1 = new Test();
Test t2 = new Test(10);
}
}
 

What is the output?


Question 2

 
 
class Student {
Student() {
System.out.println(“No argument”);
}
 
Student(int x) {
System.out.println(“Integer”);
}
 
Student(String x) {
System.out.println(“String”);
}
 
public static void main(String[] args) {
new Student();
new Student(10);
new Student(“Java”);
}
}
 

Predict the output.


Question 3

 
 
class Demo {
 
Demo() {
this(100);
System.out.println(“Default”);
}
 
Demo(int x) {
System.out.println(“Parameterized”);
}
 
public static void main(String[] args) {
Demo d = new Demo();
}
}
 

What is the output and why?


C. Find the Error

Question 4

Identify the error:

 
 
class Student {
 
void Student() {
System.out.println(“Hello”);
}
 
public static void main(String[] args) {
Student s = new Student();
}
}
 

Is Student() a constructor or a method?


Question 5

What is wrong with this code?

 
 
class Test {
 
Test() {
this(10);
System.out.println(“Hello”);
this(20);
}
 
Test(int x) {
System.out.println(x);
}
}
 

D. Programming Exercises

Beginner

  1. Create a Student class with a no-argument constructor that initializes:
    • rollNo = 0
    • name = "Unknown"
    • marks = 0
  2. Create an Employee class with a parameterized constructor accepting employee number and employee name.
  3. Create a Rectangle class with a constructor that accepts length and breadth and a method to calculate area.
  4. Create a BankAccount class with a constructor that accepts account number, holder name, and balance.

Intermediate

  1. Create a Student class with the following overloaded constructors:
 
 
Student()
Student(int rollNo)
Student(int rollNo, String name)
Student(int rollNo, String name, double marks)
 

Display the details of objects created using each constructor.

  1. Create a Box class with overloaded constructors:
 
 
Box()
Box(int side)
Box(int length, int breadth, int height)
 

Calculate and display the volume.

  1. Create an Employee class with overloaded constructors:
 
 
Employee()
Employee(int empNo, String name)
Employee(int empNo, String name, double salary)
 

Display employee details.

  1. Create a Product class with overloaded constructors to initialize:
    • Product name only
    • Product name and price
    • Product name, price and quantity

Calculate the total value.

Advanced

  1. Create a Student class using constructor chaining with this() so that all constructors ultimately call:
 
 
Student(int rollNo, String name, double marks)
 
  1. Create a Person parent class and Student child class. Use super() to call the parent constructor and demonstrate the order in which constructors execute.
  2. Create an Account class with multiple constructors and use this() to avoid duplicate initialization code.
  3. Create a Time class with overloaded constructors:
 
 
Time()
Time(int hours)
Time(int hours, int minutes)
Time(int hours, int minutes, int seconds)
 

Display the time in HH:MM:SS format.

  1. Create a Mobile class with overloaded constructors for:
  • Brand only
  • Brand + model
  • Brand + model + price
  • Brand + model + price + storage
  1. Create a Book class with overloaded constructors and use this() for constructor chaining. Include suitable validation for price and quantity.
  2. Create a Student class with overloaded constructors and demonstrate the difference between constructor overloading and method overloading in the same program.