📘 Constructors in Java

Complete guide to constructors, default vs no-args constructors, overloading, and object initialization flow.


Table of Contents

Part 1: Constructor Fundamentals

Part 2: Default & No-Args Constructors

Part 3: Parameterized Constructors

Part 4: Advanced Topics

Part 5: Synthesis


1. What Is a Constructor?

A constructor is a special method used to initialize objects.

Key characteristics:

Employee e = new Employee();

📌 Key idea: Constructors prepare an object for use.


2. Key Properties of Constructors

Property Description
Name Constructor name must match class name
Return Type Constructor has no return type (not even void)
Overloading Can be overloaded
Invocation Called only once per object creation

Syntax example:

public Employee() { }

3. Types of Constructors in Java

Java commonly categorizes constructors into:

  1. Default constructor (compiler-generated)
  2. No-args constructor (user-defined)
  3. Parameterized constructor

4. Default Constructor

4.1 What Is a Default Constructor? {#4-1-what-is-a-default-constructor}

A default constructor is automatically generated by the compiler only if:

Example:

class Employee {
    int empId;
}

Compiler-generated equivalent:

Employee() {
    super();
}

📌 Important: The default constructor exists in the .class file but may not appear in decompiled source.


4.2 When Default Constructor Is NOT Generated {#4-2-when-default-not-generated}

Example:

class Employee {
    Employee(int id) { }
}

Result:

📌 Rule: If you write any constructor, Java writes none.


5. No-Args Constructor (User-Defined)

A no-args constructor is explicitly written by the developer to perform initialization without parameters.

5.1 What Is a No-Args Constructor? {#5-1-what-is-a-no-args-constructor}

A no-args constructor is a constructor:

Example:

public Employee() {
    empId = 1;
    name = null;
}

5.2 Why Define One Manually? {#5-2-why-define-one-manually}

📌 Difference from default constructor:
Default constructor is implicit,
No-args constructor is explicit.


6. Default vs No-Args Constructor Comparison

Aspect Default Constructor No-Args Constructor
Written by developer
Generated by compiler
Has logic
Visible in source code
Exists when any constructor present

7. Parameterized Constructor in Java

7.1 What Is a Parameterized Constructor? {#7-1-what-is-a-parameterized-constructor}

A parameterized constructor is a constructor that:

Example:

public Employee(int empId, String name) {
    this.empId = empId;
    this.name = name;
}

📌 Key idea: Parameterized constructors allow objects to be created with custom initial values.


7.2 Why Use a Parameterized Constructor? {#7-2-why-parameterized}

Benefits:

Example:

Employee emp = new Employee(3, "Jay");

📌 Design insight: If an object is invalid without certain values, use a parameterized constructor.


8. this Keyword & Constructor Effects

8.1 Role of this Keyword {#8-1-this-keyword}

Usage in constructor:

this.empId = empId;
this.name = name;
Symbol Refers To
this.empId instance variable
empId constructor parameter

📌 Purpose: this resolves ambiguity between instance variables and parameters.


8.2 Effect on Default Constructor {#8-2-effect-default-constructor}

When you define a parameterized constructor:

public Employee(int empId, String name) { }

Important rule:

If any constructor is explicitly defined,
Java does not generate the default constructor.

Result:

new Employee(); // ❌ compile-time error

9. Parameterized vs No-Args Constructor

Aspect No-Args Constructor Parameterized Constructor
Takes parameters
Object customization
Default values Fixed Caller-defined
Compiler-generated
Common use Frameworks Business logic

10. Constructor Overloading and Patterns

Constructor overloading allows multiple constructors in the same class:

public Employee() { }

public Employee(int empId) { 
    this.empId = empId;
}

public Employee(int empId, String name) {
    this.empId = empId;
    this.name = name;
}

10.1 What Is Constructor Overloading?

Constructor overloading means defining multiple constructors in the same class with different parameter lists (type, count, or order).

Employee(String name) { }
Employee(int empId, String name) { }

📌 Key idea: Different ways to create objects of the same class.

Note: Each constructor must have a unique parameter signature.

10.2 Why Constructor Overloading Is Useful

new Employee("John");
new Employee(3, "Jay");

📌 Design insight: Constructor overloading helps model real-world scenarios.

10.3 How Java Selects the Correct Constructor

At object creation time, Java chooses the constructor based on:

📌 Important: Constructor resolution happens at compile time.

10.4 Role of this in Overloaded Constructors

this.empId = empId;
this.name = name;

10.7 Constructor Overloading vs Method Overloading

Aspect Constructor Overloading Method Overloading
Same name Yes (class name) Yes
Return type Not applicable Can differ
Inheritance
Polymorphism Compile-time
Purpose Object creation Behavior

10.8 Common Interview Pitfalls (Overloading)

10.9 One-Line Mental Model

Constructor overloading = multiple ways to create objects
Constructor overriding = not possible


11. Constructors and Object Creation Flow

Employee e = new Employee();

Execution order:

  1. Memory allocated
  2. Instance variables assigned default values
  3. Constructor body executed
  4. Object reference returned

12. Constructors and Inheritance

12.1 Constructors Are NOT Overridden (Very Important)

Unlike methods:

📌 Reason: Constructors are not inherited by subclasses.

12.2 Why Constructor Overriding Is Not Possible

class A { A() { } }
class B extends A { B() { } } // NOT overriding

📌 Key rule: Constructors belong to their own class only.

Key points:

📌 Important: Parent constructor executes before child constructor.


13. Constructor Chaining in Java

Constructor chaining is the process of calling one constructor from another to reuse initialization logic.

Java supports constructor chaining using:

13.1 Constructor Chaining using this() {#13-1-this-chaining}

What is this()?

this() is used to call another constructor of the same class.

EmployeeChainingThis() {
    this(10);
}

📌 Key rule: this() must be the first statement in the constructor.

13.2 Why Use this() for Constructor Chaining? {#13-2-why-this}

this(empId, "Employee");

📌 Design insight: One constructor should do the actual initialization; others delegate to it.

13.3 Constructor Chaining Flow (this()) {#13-3-chaining-flow}

In your example:

EmployeeChainingThis()
 → EmployeeChainingThis(int)
   → EmployeeChainingThis(int, String)

📌 Important: Only one constructor executes the field assignments.

13.4 Constructor Chaining using super() {#13-4-super-chaining}

What is super()?

super() is used to call a constructor of the parent class.

super(age);

📌 Purpose: Ensures parent state is initialized before child state.

13.5 Implicit super() Call {#13-5-implicit-super}

Scientist() {
    System.out.println("Scientist constructor : no args");
}

Java automatically inserts:

super();

📌 Rule: If no constructor call is written, Java inserts super() by default.

13.6 Constructor Execution Order (Very Important) {#13-6-execution-order}

new Scientist();

Execution order:

  1. Parent constructor (Person)
  2. Child constructor (Scientist)

📌 Golden rule: Parent constructors always execute before child constructors.

13.7 Parameterized super() Call {#13-7-parameterized-super}

Scientist(int empId, int age) {
    super(age);
    this.empId = empId;
}

Why explicit super(age) is required?

13.8 Rules to Remember (Must-Memorize) {#13-8-rules}

13.9 this() vs super() (Quick Comparison) {#13-9-comparison}

Aspect this() super()
Calls constructor of Same class Parent class
Used for Code reuse Inheritance initialization
First statement Mandatory Mandatory
Multiple use

13.10 One-Line Mental Models {#13-10-mental-model}

13.11 Final Carry-Forward Points {#13-11-carry-forward}


14. Private Constructors (Controlled Instantiation)

14.1 What Is a Private Constructor? {#14-1-private-constructor}

A private constructor is declared with the private access modifier and cannot be called from outside the class.

private Employee() { }

📌 Key idea: Private constructors prevent direct object creation.

14.2 Why Use a Private Constructor? {#14-2-why-private}

Private constructors are used to:

Common use cases:

14.3 Effect of a Private Constructor {#14-3-effect}

Employee emp = new Employee(); // ❌ compile-time error

Reason: Constructor is private and not accessible outside the class.

📌 Rule: If all constructors are private, no other class can instantiate the class directly.

14.4 How Object Creation Still Works (Factory Method) {#14-4-factory-method}

public static Employee getInstance() {
    return new Employee();
}

Why getInstance() must be static:

📌 Important: A private constructor can be called only from within the same class.

14.5 Object Creation Flow in Your Example {#14-5-flow}

Employee emp = Employee.getInstance();

Steps:

  1. getInstance() is called using the class name
  2. Method calls the private constructor internally
  3. Object is created and returned

14.6 Private Constructor vs No-Args Constructor {#14-6-private-vs-no-args}

Aspect No-Args Constructor Private Constructor
Access Public / default Private
Object creation Allowed everywhere Restricted
Used for Default initialization Controlled instantiation
Typical use POJOs, frameworks Singleton, factories

14.7 Private Constructor and Singleton Pattern {#14-7-singleton}

Your code forms the foundation of a Singleton:

private Employee() { }

public static Employee getInstance() { }

📌 Concept: Ensures object creation happens in a controlled way. (Full singleton adds caching + thread safety.)

14.8 Important Rules About Private Constructors {#14-8-rules}

📌 Interview insight: Utility classes often use private constructors to prevent instantiation.

14.9 One-Line Mental Model {#14-9-mental-model}

Private constructor → no direct object creation allowed

14.10 Final Carry-Forward Points {#14-10-carry-forward}


15. Constructor Safety and Design

Parameterized constructors help ensure:

📌 Best practice: Prefer parameterized constructors for mandatory fields.


16. Common Interview Pitfalls

Statement True/False
Constructors are methods ❌ False
Constructors can be static ❌ False
Constructors can be final ❌ False
Constructors can be private ✅ True
Constructor overloading is allowed ✅ True

17. One-Line Mental Models

Concept Mental Model
Constructor → object initialization
Default constructor → compiler-provided (when no constructor defined)
No-args constructor → developer-provided, fixed setup
Parameterized constructor → controlled setup with custom values
Private constructor → controlled instantiation via factory/singleton

18. Final Carry-Forward Points


← Back to Java Basics Java Hub 🏠