bhylu.com

Advertisements

Java Establish Valid State at Construction

A constructor defines how an object begins its life. Use it to require the facts that the object needs rather than leaving every caller to remember several setter calls.

Understand the idea

A constructor has the class name and no return type. It can validate arguments before storing them. If any constructor is declared, Java does not automatically add a no-argument constructor for that class. Several constructors may delegate to a shared one, but keep a single clear place for a domain rule so overloaded entry points do not accept conflicting states.

Run it locally

Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.

JDK and terminal setup

javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out Main

A worked example

Java 21+ · Main.java

public class Main {
    static class Reservation {
        final String label;
        final int seats;
        Reservation(String label, int seats) {
            if (label == null || label.isBlank() || seats <= 0)
                throw new IllegalArgumentException("A label and positive seats are required");
            this.label = label;
            this.seats = seats;
        }
    }

    public static void main(String[] args) {
        Reservation booking = new Reservation("Clay", 4);
        System.out.println(booking.label + ": " + booking.seats);
    }
}

Expected output

Clay: 4

The constructor checks the label and count before assigning either final field. this.label refers to the field, while label refers to the argument. Once construction completes normally, callers can rely on this small validity rule. Validation here does not establish an external fact such as whether the workshop actually has space.

Check the official Java documentation for detailed contracts and supported options.