Kyūkei Master Hub
SCS2108 | Phase Study Card
👁️ -- opens | 0%

Phase 9B: Demystifying Constructors in Java

Constructors confuse many students because they look like methods, but act completely differently. Let's break down everything you need to know.

1. What is a Constructor in Plain English?

👶 Real-World Analogy: Birth Certificate & Factory Setup

When a baby is born, a birth certificate is immediately created with initial data: Name, Weight, Date of Birth. You don't create a baby with 0 data and fill in their name 5 years later! A Constructor is the initial setup script that assigns valid starting values to an object at the exact second it is instantiated on the heap.

The 3 Golden Rules of Constructors:

  1. A Constructor MUST have the **exact same name** as the class.
  2. A Constructor MUST have **NO return type** (not even void!).
  3. It is called **automatically once** when new is executed. You cannot call a constructor manually later like a normal method (`obj.ConstructorName()` is illegal).

2. Types of Constructors

Type How It Is Created Code Example
Implicit Default Constructor Inserted automatically by Java compiler ONLY IF you write zero constructors in your code. Sets fields to 0, null, or false. public Person() {} (Invisible/auto-generated)
Explicit No-Arg Constructor Written by you taking no parameters, setting default custom values. public Person() { this.name = "Unknown"; }
Parameterized Constructor Written by you taking parameters to set custom values upon object creation. public Person(String n) { this.name = n; }
⚠️ The Trap Examiners LOVE to Test
If you write a Parameterized Constructor in your class, Java REMOVES the automatic default constructor! If someone later tries to write Person p = new Person(); without parameters, a compile-time error occurs unless you explicitly wrote a no-arg constructor!

3. Constructor Overloading & Chaining (this() and super())

Constructor Overloading means defining multiple constructors with different parameter signatures in the same class.

Constructor Chaining Rules:

public class Person { private String name; private int age; // No-arg constructor chains to parameterized constructor using this() public Person() { this("Default Name", 18); // MUST be first line! } // Parameterized constructor public Person(String name, int age) { this.name = name; this.age = age; } }

⚡ Quick Self-Test

Q: Consider class Book { public Book(String title) {} }. Does Book b = new Book(); compile? Why or why not?

Answer: NO! Compile Error.
Because a parameterized constructor Book(String title) was defined, Java deleted the automatic default constructor. Since no zero-argument constructor exists, new Book() fails at compile-time.