Skip to content

Encapsulation: private fields, getters, setters

Protect your data

  • Encapsulation means hiding an object's data and only changing it through methods.
  • private blocks direct access from unrelated outside code. It does not validate values: constructors and mutating methods must enforce the object’s rules themselves.
  • The main tools are the words private and public.

Private balance is accessed through getBalance and deposit; validation needs explicit code

Handout

Log in or create account

IGCSE, A-Level & AP