An invariant is a rule that stays true for the entire lifetime of an object. A task title must contain visible text, and its duration must be positive. A constructor can protect these rules once instead of asking every caller to remember them. This builds on beginner constructors and private state.
Read the class declaration
Beginner used final on fields. Here final class Task has a different job: it prevents another class from extending Task and replacing its behavior. Day 3 teaches inheritance. It does not make fields immutable by itself; private final fields and the absence of mutating operations provide that guarantee here.
Some small example constructors and methods omit public. This means package-private, not private: other classes in the same package can call them. A package groups related Java types. Our flat examples all use the unnamed package, so Main can call Task's constructor and title(). A private field is accessible only within its declaring class. The multi-file project uses public operations to make its intended API explicit.
title() is an ordinary method returning a field, often called an accessor. Java does not require the alternative name getTitle(). Use the name the class actually declares.
Work through the example
The constructor trims the title before storing it. trim() returns a new string; it does not edit the original. We explicitly reject null before calling a string method. The || operator short-circuits, so the second test is skipped if the first is true.
final fields are assigned once during construction. With no setters and only immutable string/int fields, this Task cannot change after construction. That makes sharing it much easier to reason about. Immutability is a property of the design; final on a reference to a mutable list would not make the list immutable.
Before Run, write the output and identify the exact line responsible for each result. Each editor is a separate program; names and edits in one box do not carry into the next.
public class Main {
public static void main(String[] args) {
Task task = new Task(" Read ", 25);
System.out.println(task.title());
System.out.println(task.minutes());
}
}
final class Task {
private final String title;
private final int minutes;
Task(String title, int minutes) {
if (title == null || title.trim().isEmpty()) {
throw new IllegalArgumentException("title required");
}
if (minutes <= 0) {
throw new IllegalArgumentException("minutes must be positive");
}
this.title = title.trim();
this.minutes = minutes;
}
String title() {
return title;
}
int minutes() {
return minutes;
}
}Check your prediction
Read
25Compare the behavior
A failed constructor does not return a usable object. Catch an expected validation error at a place that can respond to it. Do not catch and ignore it inside the constructor: that would let an invalid instance escape. Test both sides of a boundary, including zero and the smallest valid value.
public class Main {
public static void main(String[] args) {
try {
Task invalid = new Task(0);
System.out.println(invalid.minutes());
} catch (IllegalArgumentException error) {
System.out.println(error.getMessage());
}
System.out.println(new Task(1).minutes());
}
}
final class Task {
private final int minutes;
Task(int minutes) {
if (minutes <= 0) {
throw new IllegalArgumentException("minutes must be positive");
}
this.minutes = minutes;
}
int minutes() {
return minutes;
}
}Check your prediction
minutes must be positive
1Check every path that could change valid state
An invariant is stronger than “the constructor checked this once.” It must stay true after every allowed operation. An immutable object has fewer changing paths: construction establishes valid fields, and accessors only read them. If you later add a setter, that setter must preserve the same rules too.
For a trimmed nonblank title, trace null, spaces only, padded visible text and already-normalized text. The first guard establishes a reference exists before trim is called. The next question checks the normalized meaning. Only after both succeed should assignment publish the field value.
Now compare this with minutes. Clamping an invalid negative input to 1 would satisfy the field's positivity rule but alter the caller's request. Today's contract rejects instead. An invariant describes valid stored state; the method contract additionally describes how invalid requests are handled. Both decisions deserve tests rather than relying on final or private to enforce meaning.
Practice independently
Constructors & Invariants: practice
Write a Budget with a private final limit, a constructor accepting 1 through 240 inclusive, and a limit() accessor. Demonstrate 1 and 240 work. Demonstrate 0 is rejected with limit outside range. Avoid public writable fields.
Spend a few minutes on your own first. Compile after one small change, read the first error, and check the result against the requirements rather than matching the solution's layout.
public class Main {
public static void main(String[] args) {
// Construct budgets at the boundaries.
System.out.println("Write Budget below");
}
}
// Add a Budget class here.Hint 1: the idea
Validate before assigning the field. Both lower and upper bounds belong to the contract.
Hint 2: a first step
Write the two invalid comparisons joined by OR, then assign this.limit.
Show one solution
One possible implementation follows. Compare its decisions with yours: which values can change, what inputs are accepted, and what would expose a mistake?
public class Main {
public static void main(String[] args) {
System.out.println(new Budget(1).limit());
System.out.println(new Budget(240).limit());
try {
new Budget(0);
} catch (IllegalArgumentException error) {
System.out.println(error.getMessage());
}
}
}
final class Budget {
private final int limit;
Budget(int limit) {
if (limit < 1 || limit > 240) {
throw new IllegalArgumentException("limit outside range");
}
this.limit = limit;
}
int limit() {
return limit;
}
}Expected output:
1
240
limit outside rangeChange it and test again
Add rejection checks for -1 and 241. Change the boundary to 300 and list every check that should change. Try adding a setter: which new validation responsibilities would that create? Keep the immutable version for this exercise.
Explain before moving on
Explain the difference between rejecting bad data and silently changing it to a default. Why is trimming a known title reasonable here while changing a negative duration to 1 would conceal a problem?
Completion is saved in this browser only. It does not measure mastery.