Skip to content

Latest commit

 

History

History
328 lines (225 loc) · 6.09 KB

File metadata and controls

328 lines (225 loc) · 6.09 KB

Constructors in Java

1. What is a Constructor?

A constructor is a special member of a class used to initialize objects. Whenever you do:

Student s = new Student();

The constructor of Student is automatically executed.

Key points:

  • Same name as the class

  • No return type (not even void)

  • Called automatically

  • Used to initialize object state


2. How Constructors Work Internally

When you create an object:

Student s = new Student();

Behind the scenes:

  1. JVM allocates memory on the heap for the object

  2. Default values are assigned (0, null, false…)

  3. The constructor is called

  4. this reference points to the newly created object

Memory Flow Diagram:

Heap Memory:
+---------------------+
| Student Object      |
|---------------------|
| name: null          |
| age: 0              |
+---------------------+
        ↑
        |
     this ─────────────▶ Points to the new object       

3. Default Constructor (Provided by Compiler)

If you don't write any constructor, Java automatically supplies a default constructor.

Example:

class Demo {
    int x;
}

Compiler generates:

Demo() {
    super();   // calls Object class constructor
}

Behavior:

Demo d = new Demo();
System.out.println(d.x); // 0

✅ Default constructor sets all fields to default values.


4. No-Argument Constructor (User-defined)

When you explicitly define a constructor with no parameters:

class Demo {
    Demo() {
        System.out.println("Custom no-arg constructor");
    }
}

Differences from default constructor:

  • This is not generated by compiler.
  • You can write initialization logic.

5. Parameterized Constructor

Used when you need to initialize fields with given values during object creation.

class Student {
    String name;
    int age;

    Student(String name, int age) {
        this.name = name;   // initializing fields
        this.age = age;
    }
}

Memory Behavior:

Heap Object:
name → "Ben"
age  → 20

6. Constructor Overloading

You can create multiple constructors with different parameter lists.

class Box {
    int l, w, h;

    Box() {
        l = w = h = 0;
    }

    Box(int side) {
        l = w = h = side;
    }

    Box(int l, int w, int h) {
        this.l = l;
        this.w = w;
        this.h = h;
    }
}

Key Point: Overloading = compile-time polymorphism


7. Constructor Chaining Within the Same Class

this() calls another constructor from the same class.

class Test {
    Test() {
        this(10);  // calls parameterized constructor
        System.out.println("Default constructor");
    }

    Test(int x) {
        System.out.println("Parameterized: " + x);
    }
}

Output:

Parameterized: 10
Default constructor

8. Calling Parent Constructor (super())

Every constructor (explicitly or implicitly) calls the parent class constructor using super().

class Parent {
    Parent() {
        System.out.println("Parent constructor");
    }
}

class Child extends Parent {
    Child() {
        super(); // must be first line
        System.out.println("Child constructor");
    }
}

Output:

Parent constructor
Child constructor

Memory Flow:

Child()                     Parent()
 ↓                            ↓
super() ───────────────▶ Constructor executes

What If We Don’t Write super()?

Compiler automatically inserts:

super();

This calls Object() constructor (root class).


9. Private Constructor (Restricted Object Creation)

Private constructor prevents external instantiation.

class Singleton {
    private Singleton() {}       // cannot create from outside

    static Singleton instance = null;

    static Singleton getInstance() {
        if (instance == null)
            instance = new Singleton();
        return instance;
    }
}

Used in Singleton pattern.


10. Copy Constructor (Manual Implementation)

Java doesn't have built-in copy constructor, but you can design one:

class Person {
    String name;

    Person(Person p) {      // copy constructor
        this.name = p.name;
    }
}

Memory Diagram:

p1 → name: "Ben"
p2 → name: "Ben"  (copied value)

12. Constructor vs Method

Feature Constructor Method
Name Same as class Can be anything
Return Type None Must have return type
Called Automatically ✅ Yes ❌ No
Purpose Initialize object Perform specific task
Can overload ✅ Yes ✅ Yes
Can override ❌ No ✅ Yes
Inherited ❌ No ✅ Yes
Can be abstract ❌ No ✅ Yes

13. Common Mistakes & Traps

Mistake Explanation
Writing return type in constructor Not allowed
Using this() and super() in same constructor Not allowed
Forgetting that constructor cannot be static Static methods don’t belong to objects
Trying to override constructors Constructors are not inherited

Key Takeaways

  • Constructors are used for object initialization, not object creation.

  • Compiler adds default constructor only if no constructors exist.

  • this() → same class constructor

  • super() → parent class constructor

  • Must be first line always

  • Constructors cannot be static, final, abstract, or overridden

  • Object memory allocation happens before constructor execution