Chapter 6 of 16Foundation

Classes and Objects

Model state with fields and constructors, use this and static correctly, and protect invariants by encapsulation.

30 minJava 21
01

Why it matters

Start from the concept, not the syntax

Meet a concrete situation where this idea earns its place, then state the boundary it guards.

Objects bundle state with the behavior that guards it. A class decides what data exists and which operations are legal; a constructor makes sure every instance starts valid, so bugs surface at construction time instead of three calls later.

By the end of this chapter

Public fields and constructors that accept anything let objects start life invalid, so later methods fail far away from the real cause.

  • Fields and constructors
  • this and static
  • Encapsulation
02

Mechanism

How Java expresses the concept

Walk the actual types, rules, and runtime behavior involved—the same behavior described in the Java Language Specification.

The mental model

Fields hold an object state. A constructor has the same name as the class and runs when `new` creates an instance. If you write no constructor, the compiler supplies a no-arg one; the moment you write any constructor, the default disappears.

`this` disambiguates a parameter from a field with the same name and lets one constructor call another with `this(...)`. Encapsulation means making fields private and exposing behavior through methods, so the object can protect its own invariants.

`static` belongs to the class, not any instance: a `static` field is shared by every object, and a `static` method can be called without an object. Instance methods can see static members, but static methods cannot see instance fields without an object reference.

An object is only as valid as its constructor leaves it. Validate arguments in the constructor and fail fast with an exception rather than storing an illegal state that breaks later methods.

03

Concept map

Inspect the building blocks as a whole

Use the map as a structural reference; it shows the pieces and their relationships, not an execution sequence.

Core Java

Fields, constructors, and static

A class is a blueprint; an object is an instance with its own field values. Constructors build valid objects and `this` refers to the current instance.

  1. 01Class vs instance
  2. 02Constructors
  3. 03this reference
  4. 04Encapsulation
  5. 05static members
  6. 06Fail-fast validation
04

Implementation

Encode the smallest runnable example

Write and run the code, then observe the behavior you just predicted with a real Java program.

Runnable snippet path

Predict, run, and change each example

2 focused examples
01

Encapsulate with a constructor

The constructor validates and initializes; getters expose state without exposing the field.

Account.java
public class Account {
    private final int id;
    private int balance;

    Account(int id, int opening) {
        if (opening < 0) throw new IllegalArgumentException("opening < 0");
        this.id = id;
        this.balance = opening;
    }

    int balance() { return balance; }
}

Remember

Make fields private and validate in the constructor so objects start life valid.

Change one input, predict the result, then compile or test it before continuing.

02

static shared counter

A static field is one value shared across all instances.

Counter.java
public class Counter {
    private static int created;
    Counter() { created++; }
    static int count() { return created; }
}

Remember

static state is global; prefer passing values explicitly unless truly shared.

Change one input, predict the result, then compile or test it before continuing.

05

Watch out

Break it on purpose, then repair the right layer

Predict the symptom before running the failure case, and close with the completion checklist.

Deliberate failure

  1. Break

    Expose balance as a public field and let callers set it negative

  2. Observe

    Withdrawals succeed on an already-negative account

  3. Repair

    Make fields private, validate in the constructor, and expose behavior through methods instead of raw state

Why it matters

Make fields private, validate in the constructor, and expose behavior through methods instead of raw state

Completion checklist

  • Distinguish instance members from static
  • Initialize state in a constructor
  • Protect invariants through encapsulation
06

Go deeper

Official references

The primary sources behind this chapter. Every claim above stays consistent with them.