Constructors
On the last page, we set an object's fields one by one after creating it with new. A
constructor is a special method that lets you set up all of an object's initial values
in one step, the moment it's created.
What Is a Constructor?
A constructor is a block of code that runs automatically when you create an object with new. It has two special rules:
- It must have the exact same name as the class.
- It has no return type — not even
void.
The Default Constructor
If you don't write any constructor yourself, Java automatically provides an invisible
no-argument (default) constructor for you, which is what let new Car() work on
the previous page even though we never defined one.
public class Car {
String brand;
int speed;
// no constructor written - Java silently provides:
// Car() { }
}
A Parameterized Constructor
A parameterized constructor accepts values and uses them to initialize fields right away — no more setting each field on a separate line.
public class Car {
String brand;
int speed;
// parameterized constructor
Car(String brand, int speed) {
this.brand = brand;
this.speed = speed;
}
}
// creating an object now sets both fields immediately:
Car myCar = new Car("Toyota", 120);
Using this to Avoid Naming Conflicts
Notice the constructor parameters are named exactly the same as the fields (brand, speed) —
this is common and makes code easier to read. But it creates ambiguity: inside the constructor, plain brand
refers to the parameter, not the field. The this keyword means "the current object," so
this.brand unambiguously means the field.
this to get by for now — a full page dedicated to the this keyword covers all of its uses.Constructor Overloading
Just like regular methods, a class can have multiple constructors as long as their parameter lists differ. This gives callers flexibility in how they create an object.
public class Car {
String brand;
int speed;
// no-argument constructor with sensible defaults
Car() {
this.brand = "Unknown";
this.speed = 0;
}
// parameterized constructor
Car(String brand, int speed) {
this.brand = brand;
this.speed = speed;
}
}
Car c1 = new Car(); // brand="Unknown", speed=0
Car c2 = new Car("Honda", 140); // brand="Honda", speed=140
new.