Skip to content
Thisara samuditha edited this page Jul 20, 2026 · 2 revisions

Java Constructors

A complete guide to understanding Java constructors from beginner to advanced level.


Table of Contents

  1. What is a Constructor?
  2. Why Do We Need Constructors?
  3. How Object Creation Works in Java
  4. Constructor Rules
  5. Types of Constructors
  6. Default Constructor
  7. No-Argument Constructor
  8. Parameterized Constructor
  9. Constructor Overloading
  10. Using this Keyword in Constructors
  11. Constructor Chaining
  12. Using super() in Constructors
  13. Constructor Execution Order
  14. Constructors and Inheritance
  15. Constructor Access Modifiers
  16. Private Constructors
  17. Copy Constructor in Java
  18. Constructor vs Method
  19. Initialization Blocks vs Constructors
  20. Common Constructor Mistakes
  21. Best Practices
  22. Real-World Examples
  23. Interview Questions
  24. Final Summary

1. What is a Constructor?

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

A constructor is automatically executed when an object is created using the new keyword.

Example:

class Student {

    String name;

    Student() {
        name = "Unknown";
    }
}

Creating an object:

Student student = new Student();

When the object is created, Java automatically calls:

Student()

2. Why Do We Need Constructors?

Without constructors, object initialization becomes repetitive.

Example without constructor:

class Student {

    String name;
    int age;

}

Creating objects:

Student s1 = new Student();

s1.name = "John";
s1.age = 20;

Every object requires manual initialization.

With a constructor:

class Student {

    String name;
    int age;

    Student(String name, int age){

        this.name = name;
        this.age = age;

    }
}

Now:

Student s1 = new Student("John",20);

The object is created with valid data immediately.


3. How Object Creation Works in Java

When Java executes:

Student s = new Student();

The JVM performs:

1. Allocate memory for object

        ↓

2. Initialize variables with default values

        ↓

3. Execute constructor

        ↓

4. Return object reference

Example:

class Student {

    String name;
    int age;

    Student(){

        name = "Alice";
        age = 20;

    }
}

Before constructor:

name = null
age = 0

After constructor:

name = Alice
age = 20

4. Constructor Rules

A constructor must follow these rules:

Rule 1: Constructor name must match class name

Correct:

class Student {

    Student(){

    }
}

Wrong:

class Student {

    student(){

    }
}

Rule 2: Constructor has no return type

Correct:

Student(){

}

Wrong:

void Student(){

}

The second one is a method, not a constructor.


Rule 3: Constructor is called automatically

You cannot call it like a normal method.

Wrong:

Student();

Correct:

new Student();

Rule 4: Constructors can be overloaded

A class can have multiple constructors.


Rule 5: Constructors cannot be overridden

Constructors belong to object creation, not inheritance.


5. Types of Constructors

Java has three commonly used constructor types:

Type Description
Default Constructor Created automatically by compiler
No-Argument Constructor Programmer-created constructor without parameters
Parameterized Constructor Constructor that accepts values

6. Default Constructor

A default constructor is automatically created by Java if no constructor is written.

Example:

class Student {

}

Compiler creates:

Student(){

}

Now:

Student s = new Student();

works correctly.


Important Note

If you create any constructor, Java will not create a default constructor.

Example:

class Student {

    Student(String name){

    }

}

Now:

Student s = new Student();

causes:

Compile Error

7. No-Argument Constructor

A no-argument constructor is a constructor without parameters.

Example:

class Student {

    String name;

    Student(){

        name = "Unknown";

    }

}

Usage:

Student s = new Student();

8. Parameterized Constructor

A parameterized constructor accepts values.

Example:

class Student {

    String name;
    int age;


    Student(String name, int age){

        this.name = name;
        this.age = age;

    }

}

Usage:

Student s = new Student("John",21);

Object state:

name = John
age = 21

9. Constructor Overloading

Constructor overloading means having multiple constructors with different parameters.

Example:

class Student {


    Student(){

    }


    Student(String name){

    }


    Student(String name, int age){

    }

}

Java decides which constructor to call based on arguments.

Example:

new Student();

new Student("John");

new Student("John",20);

10. Using this Keyword in Constructors

this refers to the current object.

It is commonly used to differentiate instance variables and constructor parameters.

Example:

class Student {

    String name;


    Student(String name){

        this.name = name;

    }

}

Without this:

name = name;

Both refer to the parameter.

With this:

this.name

means object variable.


11. Constructor Chaining

Constructor chaining means calling one constructor from another constructor.

It avoids duplicate code.

Example:

class Student {


    Student(){

        this("Unknown");

    }


    Student(String name){

        System.out.println(name);

    }

}

Execution:

Student()

    ↓

Student(String)

    ↓

Print name

Rules of this()

  • Must be the first statement.
  • Can only call another constructor in the same class.
  • Cannot call multiple constructors.

Example:

Student(){

    this("John");

    System.out.println("Hello");

}

Valid.


12. Using super() in Constructors

super() calls the parent class constructor.

Example:

class Animal {

    Animal(){

        System.out.println("Animal Constructor");

    }

}


class Dog extends Animal {


    Dog(){

        super();

        System.out.println("Dog Constructor");

    }

}

Output:

Animal Constructor

Dog Constructor

13. Constructor Execution Order

In inheritance, parent constructors execute before child constructors.

Example:

class A {

    A(){

        System.out.println("A");

    }

}


class B extends A {

    B(){

        System.out.println("B");

    }

}


class C extends B {

    C(){

        System.out.println("C");

    }

}

Creating:

new C();

Output:

A

B

C

Order:

Parent
  ↓
Child
  ↓
Grand Child

14. Constructors and Inheritance

Constructors are not inherited.

Example:

class Parent {

    Parent(){

    }

}


class Child extends Parent {

}

Child does not inherit the constructor.

Instead, Java automatically calls:

super();

15. Constructor Access Modifiers

Constructors can have access modifiers.

Public Constructor

Accessible everywhere.

public Student(){

}

Protected Constructor

Accessible in subclasses and same package.

protected Student(){

}

Package Private Constructor

No modifier.

Student(){

}

Private Constructor

Accessible only inside the class.

private Student(){

}

16. Private Constructors

Private constructors prevent object creation from outside the class.

Common uses:

  • Singleton Pattern
  • Utility Classes
  • Factory Pattern

Example:

class Database {


    private Database(){

    }


}

Now:

new Database();

is impossible.


Singleton Example

class Database {


    private static Database instance;


    private Database(){

    }


    public static Database getInstance(){

        if(instance == null){

            instance = new Database();

        }

        return instance;

    }

}

Only one object can exist.


17. Copy Constructor in Java

Java does not provide built-in copy constructors.

But we can create our own.

Example:

class Student {

    String name;


    Student(String name){

        this.name = name;

    }


    Student(Student other){

        this.name = other.name;

    }

}

Usage:

Student s1 = new Student("John");

Student s2 = new Student(s1);

18. Constructor vs Method

Constructor Method
Initializes objects Performs operations
Same name as class Any valid name
No return type Has return type
Called automatically Called manually
Cannot be overridden Can be overridden
Runs during object creation Runs when called

19. Initialization Blocks vs Constructors

Java initialization block:

class Student {


    {
        System.out.println("Initialization Block");
    }


    Student(){

        System.out.println("Constructor");

    }

}

Execution:

Initialization Block

↓

Constructor

20. Common Constructor Mistakes

Mistake 1: Adding return type

Wrong:

void Student(){

}

Correct:

Student(){

}

Mistake 2: Wrong class name

Wrong:

student(){

}

Correct:

Student(){

}

Mistake 3: Forgetting constructor chaining rules

Wrong:

Student(){

    System.out.println("Hello");

    this("John");

}

this() must be the first statement.


Mistake 4: Creating unnecessary constructors

Too many constructors make classes difficult to maintain.


21. Best Practices

1. Initialize required fields in constructors

Good:

Student(String name){

    this.name=name;

}

2. Use constructor validation

Example:

Student(int age){

    if(age < 0){

        throw new IllegalArgumentException();

    }

}

3. Keep constructors simple

Avoid:

  • Database calls
  • Network calls
  • Heavy calculations

4. Use final fields where possible

Example:

class Student {

    private final int id;


    Student(int id){

        this.id=id;

    }

}

22. Real-World Examples

User Class

class User {

    private String username;
    private String email;


    User(String username,String email){

        this.username=username;
        this.email=email;

    }

}

Bank Account

class BankAccount {


    private String accountNumber;

    private double balance;


    BankAccount(String accountNumber,double balance){

        this.accountNumber = accountNumber;
        this.balance = balance;

    }

}

Product Class

class Product {


    String name;

    double price;


    Product(String name,double price){

        this.name=name;
        this.price=price;

    }

}

23. Interview Questions

Q1. Can constructors be overloaded?

Yes.


Q2. Can constructors be overridden?

No.


Q3. Can constructors be inherited?

No.


Q4. Can constructors be static?

No.


Q5. Can constructors be final?

No.


Q6. Can constructors be private?

Yes.

Used for Singleton pattern.


Q7. Can constructor throw exceptions?

Yes.

Example:

Student() throws Exception{

}

Q8. What happens if a constructor is not defined?

Java creates a default constructor automatically.


Q9. Why use this()?

To call another constructor in the same class.


Q10. Why use super()?

To call the parent class constructor.


24. Final Summary

Concept Description
Constructor Initializes objects
Same name as class Required
Return type Not allowed
Called automatically Yes
Default constructor Compiler generated
Parameterized constructor Initializes with values
Overloading Multiple constructors
this() Calls another constructor
super() Calls parent constructor
Inherited No
Overridden No
Private constructors Used for Singleton and utility classes
Best practice Keep constructors simple

Final Takeaways

  • Constructors are responsible for creating valid objects.
  • Every Java object creation involves constructor execution.
  • Use parameterized constructors to initialize required values.
  • Use this() for constructor reuse inside a class.
  • Use super() when working with inheritance.
  • Constructors are not methods and follow different rules.
  • Good constructor design improves code readability, safety, and maintainability.

Clone this wiki locally