Lesson 17 / 38
Constructors
Initialise object state with constructors, rely on the implicit no-arg default, and chain to other constructors in the same class with this(...).
Defining constructors
A constructor has the class name and no return type. If you write none, Java supplies a no-arg default. this(...) calls another constructor in the same class.
public class Point {
private final int x, y;
public Point(int x, int y) { this.x = x; this.y = y; }
public Point() { this(0, 0); } // delegate
}Overloaded constructors
Like methods, constructors can be overloaded — several with the same class name but different parameter lists. Callers pick whichever shape suits them.
public class Rectangle {
private final double width, height;
public Rectangle(double width, double height) {
this.width = width; this.height = height;
}
public Rectangle(double side) { // square
this(side, side);
}
}
new Rectangle(4, 5);
new Rectangle(3); // 3x3 squareInitialization order
When an object is created, Java runs: field default values → instance initializer blocks and field initializers, in source order → the constructor body. In a subclass, the superclass constructor always runs first (implicitly super() if you don't call it).