📘 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
- 4. Default Constructor
- 5. No-Args Constructor (User-Defined)
- 6. Default vs No-Args Constructor Comparison
Part 3: Parameterized Constructors
- 7. Parameterized Constructor in Java
- 8. this Keyword & Constructor Effects
- 9. Parameterized vs No-Args Constructor
Part 4: Advanced Topics
- 10. Constructor Overloading and Patterns
- 11. Constructors and Object Creation Flow
- 12. Constructors and Inheritance
- 13. Constructor Chaining in Java
- 14. Private Constructors (Controlled Instantiation)
- 15. Constructor Safety and Design
- 16. Common Interview Pitfalls
Part 5: Synthesis
1. What Is a Constructor?
A constructor is a special method used to initialize objects.
Key characteristics:
- It is called automatically when an object is created using
new - It initializes instance variables
- It sets the initial state of an object
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:
- Default constructor (compiler-generated)
- No-args constructor (user-defined)
- 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:
- No constructor is explicitly defined in the class
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:
- Compiler does not generate default constructor
new Employee()→ ❌ compile-time error
📌 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:
- Written by the developer
- Takes no parameters
- Explicitly initializes fields
Example:
public Employee() {
empId = 1;
name = null;
}
5.2 Why Define One Manually? {#5-2-why-define-one-manually}
- To assign default values
- To execute initialization logic
- To keep compatibility with frameworks
- To make behavior explicit
📌 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:
- Accepts parameters
- Initializes object state using provided values
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:
- To avoid partially initialized objects
- To enforce mandatory data during object creation
- To make object state explicit and meaningful
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
- Allows flexible object creation
- Supports different initialization needs
- Improves API usability
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:
- Number of arguments
- Argument types
- Order of parameters
📌 Important: Constructor resolution happens at compile time.
10.4 Role of this in Overloaded Constructors
this.empId = empId;
this.name = name;
- Refers to the current object
- Avoids ambiguity
- Ensures correct field initialization
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)
- Constructors cannot be overridden
- Constructors are not inherited
- Overloading depends only on parameters
- Access modifiers can differ between constructors
- Defining any constructor suppresses the default constructor
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:
- Memory allocated
- Instance variables assigned default values
- Constructor body executed
- Object reference returned
12. Constructors and Inheritance
12.1 Constructors Are NOT Overridden (Very Important)
Unlike methods:
- Constructors do not participate in inheritance
- Constructors cannot be overridden
📌 Reason: Constructors are not inherited by subclasses.
12.2 Why Constructor Overriding Is Not Possible
- Constructor name must match the class name
- A subclass has a different class name
- Therefore, overriding rules do not apply
class A { A() { } }
class B extends A { B() { } } // NOT overriding
📌 Key rule: Constructors belong to their own class only.
Key points:
- Constructor is not inherited
- First statement of constructor is always:
super()(implicit or explicit)
📌 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:
this()→ within the same classsuper()→ between parent and child classes
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}
- Avoids duplicate initialization code
- Centralizes object initialization
- Improves maintainability
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:
- Parent constructor (Person)
- 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?
- Parent has a parameterized constructor
- No default constructor is used in this path
- Parent state must be initialized explicitly
13.8 Rules to Remember (Must-Memorize) {#13-8-rules}
this()andsuper()cannot be used together- They must be the first statement in a constructor
- Constructors cannot call both
this()andsuper() - Constructor chaining happens only once per object creation
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}
this()→ reuse constructor in same classsuper()→ initialize parent part of object
13.11 Final Carry-Forward Points {#13-11-carry-forward}
- Constructor chaining avoids duplicate code
this()chains constructors within the same classsuper()chains constructors across inheritance- Parent constructors always run first
- Proper chaining leads to clean and maintainable code
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:
- Restrict object creation
- Control how instances are created
- Enforce design patterns
Common use cases:
- Singleton pattern
- Utility classes
- Factory methods
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:
- No object exists to call an instance method
- Static methods belong to the class
- They can call private constructors internally
📌 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:
getInstance()is called using the class name- Method calls the private constructor internally
- 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}
- Constructors can be private
- Constructors cannot be inherited
- A class with only private constructors:
- Cannot be extended
- Cannot be instantiated externally
📌 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}
- Private constructors restrict instantiation
- Static factory methods enable controlled creation
- Used in Singleton and utility classes
- Constructor access level controls object lifecycle
- Private constructors are a design tool, not a limitation
15. Constructor Safety and Design
Parameterized constructors help ensure:
- Objects are created in a valid state
- Required fields are initialized
- Fewer runtime errors due to uninitialized data
📌 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
- Constructors initialize objects and are called once per object creation
- Default constructor exists only if no constructor is explicitly defined
- No-args constructor gives explicit control with fixed values
- Parameterized constructors initialize objects with custom, caller-provided data
- Parameterized constructors suppress the default constructor
- Private constructors restrict direct instantiation; use static factory methods
- Constructor name must equal the class name
- Constructors have no return type (not even
void) thiskeyword resolves ambiguity between instance variables and parameters- Constructor overloading allows multiple constructors with different signatures
- Prefer parameterized or private constructors to ensure valid object state