Lesson 3 / 25

Constructors, this and Static Members

Write constructors, overload them, chain them and use static members correctly.

Creating objects in a valid state

A constructor runs when an object is created and should leave it in a valid state. In Java it has the class name and no return type; in Python it is __init__. If you write no constructor, Java provides a default no-argument one; as soon as you write any constructor, that default disappears. Constructors can be overloaded (several with different parameter lists), and one can call another with this(...) to avoid duplication (constructor chaining). Inside methods, this refers to the current object and resolves name clashes between fields and parameters (this.name = name). Static fields and methods belong to the class: a static int count is shared by all objects, and a static method such as Math.max is called on the class without any instance; static methods cannot use this. Use static members for things that are truly class-wide, such as constants and factory methods, and avoid using static fields as hidden global state.

Overloaded and chained constructors with a static counter

Every constructor path ends in the one that validates.

public class Rectangle {
    private static int created = 0;          // shared by all Rectangles
    private final double width;
    private final double height;

    public Rectangle(double width, double height) {
        if (width <= 0 || height <= 0) {
            throw new IllegalArgumentException("sides must be positive");
        }
        this.width = width;
        this.height = height;
        created++;
    }

    public Rectangle(double side) {           // overloaded: a square
        this(side, side);                     // chain to the main constructor
    }

    public double area() { return width * height; }

    public static int createdCount() { return created; }   // no 'this' here
}

Rectangle r1 = new Rectangle(3, 4);
Rectangle r2 = new Rectangle(5);
int n = Rectangle.createdCount();             // 2

Validate in one place

Put validation in one primary constructor and chain the others to it. Duplicated checks in several constructors drift apart over time, and one path eventually forgets a rule.

Quick check: What happens to Java's default no-argument constructor once you write any constructor for a class?

  • It is still generated automatically
  • It becomes static
  • It is no longer provided; you must write it yourself if you need it
  • It becomes private
Answer

It is no longer provided; you must write it yourself if you need it — Java only supplies the default constructor when the class declares no constructors.