Topic 3.4 — Constructors
Goal: explain what constructors do, recognize constructor headers, and write constructors that initialize instance variables (including overloaded constructors).
The big idea
A constructor runs when you create an object with new.
Its job is to set up the object’s starting state (initialize instance variables).
If you don’t write any constructor, Java provides a default no-arg constructor (in some cases).
Constructor rules you must know
- Constructor name == class name
- No return type (not even
void) - Usually
public - Used to initialize instance variables
Basic example (no-arg constructor)
public class Counter {
private int value;
public Counter() { // constructor
value = 0;
}
}
When you do new Counter(), the constructor runs and sets value to 0.
Overloaded constructors
A class can have multiple constructors as long as their parameter lists are different.
public class Counter {
private int value;
public Counter() {
value = 0;
}
public Counter(int start) {
value = start;
}
}
Same constructor name, different parameters → that’s overloading.
Calling one constructor from another
You can reuse initialization code by calling this(...) inside a constructor.
(If your teacher allows it, it’s a clean design.)
public Counter() {
this(0); // calls Counter(int start)
}
public Counter(int start) {
value = start;
}
If used, this(...) must be the first statement in the constructor.
Common mistakes
- Writing a return type (turns it into a method, not a constructor).
- Forgetting to initialize instance variables.
- Parameter names confusing you: use
this.fieldwhen needed (Topic 3.9).
// Not a constructor (has return type!)
public void Counter() { ... } // ❌
Quick self-check
- When does a constructor run?
- What two things must match for a constructor header to be valid?
- What does it mean to “overload” constructors?
- Why do we write constructors instead of leaving variables uninitialized?
- Spot the bug: why is
public void MyClass()not a constructor?