[!NOTE] When you use the
newkeyword, Java executes a special method called a Constructor right as the object is being built. This is your opportunity to force required parameters upon creation.
The Constructor Method
A constructor is a highly specialized method that serves exactly one purpose: initializing the state of a new object.
Rules of a Constructor:
- Its name must exactly match the Class name.
- It cannot have a return type (not even
void). - It is called automatically the moment
newis executed.
public class Car {
String modelName;
int manufacturingYear;
// This is the Constructor!
public Car(String name, int year) {
modelName = name;
manufacturingYear = year;
System.out.println("A new " + name + " has rolled off the assembly line.");
}
public static void main(String[] args) {
// You MUST provide the parameters when calling 'new'!
Car myCar = new Car("Mustang", 1969);
}
}
Constructor Overloading
What if you want to give developers multiple ways to build an object? Maybe occasionally they know the manufacturing year, but sometimes they just want a default "Blank" car?
You can overload constructors by writing multiple constructors with different parameter signatures. The JVM will automatically figure out which one you are trying to use based on the arguments you pass.
public class User {
String email;
String role;
// Constructor 1: Fully custom
public User(String emailArg, String roleArg) {
email = emailArg;
role = roleArg;
}
// Constructor 2: Assumes a default 'guest' role!
public User(String emailArg) {
email = emailArg;
role = "guest";
}
public static void main(String[] args) {
User admin = new User("admin@site.com", "admin_role"); // Calls Constructor 1
User random = new User("rando@site.com"); // Calls Constructor 2
}
}
[!CAUTION] If you do not write a single constructor in your class, Java secretly compiles an invisible, empty "Default Constructor" for you so
new Car()works. However, the moment you explicitly write any parameterized constructor, the invisible default one is destroyed! You must manually re-add an emptypublic Car() {}if you want it back.
Constructors Protect Object Validity
A constructor should leave an object ready to use. If a User must always have an email, the constructor is a good place to require it. This prevents half-created objects from spreading through your program.
Validate During Construction
class User {
private String email;
User(String email) {
if (email == null || email.isBlank()) {
throw new IllegalArgumentException("Email is required");
}
this.email = email;
}
}
Throwing an exception here is better than allowing a broken User object and discovering the problem much later.
Constructor Chaining
class Product {
String name;
double price;
Product(String name) {
this(name, 0.0);
}
Product(String name, double price) {
this.name = name;
this.price = price;
}
}
this(...) calls another constructor in the same class. It helps keep default setup logic in one place.
Common Mistakes
- Adding a return type to a constructor, which turns it into a normal method.
- Writing validation in many methods instead of creating valid objects from the start.
- Forgetting that adding one constructor removes Java's implicit no-argument constructor.
- Duplicating initialization logic across overloaded constructors.
Mini Practice
Create a Course class whose constructor requires a non-empty title and a positive duration. Add an overloaded constructor that uses a default duration.
Practice Lab: Valid Objects From Birth
Use constructors to prevent incomplete objects.
- Create a
Courseclass with title, duration hours, and difficulty. - Write a constructor requiring all three values.
- Reject empty title and non-positive duration with
IllegalArgumentException. - Add an overloaded constructor that sets difficulty to
beginner.
Goal: Practice required initialization, validation, and constructor overloading.
Revision Checkpoint
- Constructor name: Must match the class name.
- No return type: Constructors do not declare
void. - Purpose: Initialize a new object into a valid state.
- Overloading: Multiple constructors can provide different creation paths.
this(...): Calls another constructor in the same class.
Before the quiz: Identify whether a code block is a constructor or a normal method.