Skip to main content
PreparationZone Logo
PrepZone

Encapsulation and Abstraction

Two ideas that are constantly confused: hiding data versus hiding complexity.

Pass checkpoint below

Read these first

Why this matters

  • These two are routinely given as each other's definitions, and a precise answer is a quick signal of real understanding.
  • Weak encapsulation is the root cause of the bug where an object is valid when you create it and invalid an hour later.
  • Choosing the right abstraction determines how much of your codebase has to change when a requirement does.
EncapsulationHide the data, expose behaviour
AbstractionPublish intent, hide mechanics
InheritanceReuse a parent contract
PolymorphismOne call, many outcomes
Encapsulation and abstraction decide what the outside world can see. Inheritance and polymorphism decide how types relate and which code actually runs.

Encapsulation: the object guards its own state

The mechanism is simple — private fields, public methods — but the point is the invariant, the rule that must always hold.

Java
Loading compiler…

The invariant is "balance is never negative". Because balance is private and there is no setter, that rule holds for the entire life of the object. No caller can break it, even by mistake.

The getter-and-setter habit

Generating a getter and setter for every field is the most common misunderstanding of encapsulation. The question to ask is what operation the caller actually wants.

AspectField-oriented APIOperation-oriented API
ShapegetStatus() / setStatus()approve() / reject()
Where rules liveScattered across every callerInside the class, once
Invalid statesReachable by any callerUnreachable
Reading the codeWhat does setting status to 2 mean?Obvious from the name
Changing the ruleFind every call siteEdit one method
  • Shape

    Field-oriented APIgetStatus() / setStatus()
    Operation-oriented APIapprove() / reject()
  • Where rules live

    Field-oriented APIScattered across every caller
    Operation-oriented APIInside the class, once
  • Invalid states

    Field-oriented APIReachable by any caller
    Operation-oriented APIUnreachable
  • Reading the code

    Field-oriented APIWhat does setting status to 2 mean?
    Operation-oriented APIObvious from the name
  • Changing the rule

    Field-oriented APIFind every call site
    Operation-oriented APIEdit one method

Expose what callers want to do, not the fields that happen to implement it.

The rest of this guide is part of Pro

Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.

Still to come · 5 sections

  • Defensive copying
  • Abstraction: hiding complexity, not data
  • The two side by side
  • Package-private as a design tool
  • Common misreadings

Test yourself

Answer these before moving on — recall is what makes it stick.