Chapters & contents Lesson 5 of 20
3 min read
Java foundationsExpanded reading

Classes that start in a valid state

Model a small Java object around responsibilities and invariants.

What you’ll learn

  • Distinguish a class and an object
  • Initialize state through a constructor
  • Keep validation close to the state it protects

Start with a responsibility

A class is useful when some state and the operations that govern it belong together. Consider a library copy with an identifier and a loan status. The important design question is not simply which nouns appear in the description. Ask which component should decide whether lending is allowed and how a return changes the state. A class that merely exposes every field may move the validation burden to every caller, producing inconsistent rules across the application.

Separate the class from its objects

The class describes fields, constructors, and methods; an object is a particular runtime instance. Two objects can share a class while holding different identifiers or states. Reference variables can refer to an object, and copying a reference does not create an independent object. This distinction matters when one part of the application changes a shared instance. Decide whether you need one shared entity or an independent value before choosing how to pass it around.

Use construction to establish rules

A constructor initializes a new object. It should establish the conditions required for public operations to work sensibly, such as a nonempty identifier or a nonnegative capacity. If a required value is invalid, reject it through an intentional error contract rather than creating an object that will fail unpredictably later. Avoid doing unrelated network work during simple object construction. Dependencies and failures become easier to understand when creation has a focused responsibility.

Expose operations that preserve invariants

An invariant is a condition that should remain true after each public operation completes. If availableCopies must never be negative, a borrowing method should check availability before decreasing the count. Merely making a field private is not enough when a public setter can assign any value without validation. Offer operations that express domain actions, and return or throw a meaningful result when the action cannot be performed. Keep the rule in one place.

Test the lifecycle

Create an object with valid initial data, perform a permitted action, and verify the resulting behavior. Then attempt the same action at a boundary where it should fail. Include construction with invalid values and repeated transitions, such as returning an item that is already available. Tests should describe public behavior rather than depend on the exact names of private fields. This allows internal representation to improve while callers continue to rely on the same contract.

Try it yourself

A seat counter has capacity three. Propose constructor rules and an operation for reserving one seat.

Show a possible solution

Require a nonnegative capacity, initialize reservations to zero, and provide reserve() that succeeds only when reservations are below capacity. The operation must preserve zero <= reservations <= capacity and communicate a full result clearly.

Check your understanding

Try 14 questions across java foundations. Read each explanation and revisit anything that needs another pass.

Practise this subject

Go to the source

Use these primary references to check details and explore the topic further.

Saved in this browser. Signed-in progress syncs to your account.