Java Constructors
Setting every field by hand after new is tedious and error-prone — it's easy to forget one. A constructor is a special method that runs automatically when an object is created, so the object starts life in a valid state.
A constructor:
- has exactly the same name as the class,
- has no return type (not even
void), - runs once per object, as part of
new.
A first constructor
class Car {
String brand;
int year;
Car(String b, int y) {
brand = b;
year = y;
System.out.println("Built a " + brand);
}
}
class Main {
public static void main(String[] args) {
Car c1 = new Car("Volvo", 2021);
Car c2 = new Car("Mazda", 2018);
System.out.println(c1.brand + " " + c1.year);
System.out.println(c2.brand + " " + c2.year);
}
}Built a Volvo
Built a Mazda
Volvo 2021
Mazda 2018
The arguments in new Car("Volvo", 2021) are passed to the constructor's parameters.
The default constructor
If you write no constructor at all, Java silently adds an empty no-argument constructor, which is why new Book() worked in earlier chapters. But as soon as you declare any constructor, that free one disappears:
class Car {
Car(String brand) { ... }
}
Car c = new Car(); // error: constructor Car in class Car cannot be applied to given typesOverloaded constructors and this(...)
Like methods, constructors can be overloaded. One constructor can call another with this(...) — it must be the first statement — so the real initialisation logic lives in one place:
class Pizza {
String size;
String topping;
boolean extraCheese;
Pizza(String size, String topping, boolean extraCheese) {
this.size = size;
this.topping = topping;
this.extraCheese = extraCheese;
}
Pizza(String size, String topping) {
this(size, topping, false);
}
Pizza() {
this("medium", "margherita");
}
@Override
public String toString() {
return size + " " + topping + (extraCheese ? " + extra cheese" : "");
}
}
class Main {
public static void main(String[] args) {
System.out.println(new Pizza());
System.out.println(new Pizza("large", "pepperoni"));
System.out.println(new Pizza("small", "funghi", true));
}
}medium margherita
large pepperoni
small funghi + extra cheese
Here the parameters have the same names as the fields, so this.size means "the field" and plain size means "the parameter". The next chapter explains this in detail.
Validating in the constructor
A constructor is the perfect place to reject bad data, so an invalid object can never exist:
class Rectangle {
final double width;
final double height;
Rectangle(double width, double height) {
if (width <= 0 || height <= 0) {
throw new IllegalArgumentException("Sides must be positive");
}
this.width = width;
this.height = height;
}
double area() {
return width * height;
}
}
class Main {
public static void main(String[] args) {
Rectangle r = new Rectangle(3, 4.5);
System.out.println("Area: " + r.area());
try {
new Rectangle(-1, 2);
} catch (IllegalArgumentException e) {
System.out.println("Rejected: " + e.getMessage());
}
}
}Area: 13.5
Rejected: Sides must be positive
final fields that aren't initialised at the declaration must be assigned in every constructor — the compiler checks it.
Order of initialisation
When you call new, Java runs things in a fixed order: fields get default values, then field initialisers run (top to bottom), then the constructor body:
class Demo {
int a = 5;
int b;
Demo() {
System.out.println("in constructor, a = " + a + ", b = " + b);
b = a * 2;
}
}
class Main {
public static void main(String[] args) {
Demo d = new Demo();
System.out.println("after new, b = " + d.b);
}
}in constructor, a = 5, b = 0
after new, b = 10
| Constructor | Method |
|---|---|
| name = class name | any name |
| no return type | has a return type or void |
called by new |
called explicitly |
| not inherited | inherited by subclasses |
Test yourself
Which is a valid constructor for class Book?
- void Book() {}
- Book() {}
- book() {}
- Book void() {}
A class declares only Lamp(int watts). What happens with new Lamp()?
- watts defaults to 0
- Compile error
- Runtime exception
- Java uses the default constructor
Where must this(...) appear inside a constructor?
- Anywhere
- As the last statement
- As the first statement
- Only in static methods