Skip to lesson

Must-do problems: Encapsulation

In every problem the class must protect itself: fields are private, every change goes through a method that checks the rules first, and a refused command leaves the object exactly as it was. Write the class, test it from main on the samples, and run every test before opening a hint.

What you will learn

What you will learn

  • Keep every field private and change it only through methods that check the rules
  • Validate in setters and constructors so an object can never hold bad data
  • Report a refused change clearly with a boolean, a message or an exception
  • Protect private arrays with defensive copies and keep derived values as getters

Sign in to continue this lesson

Create an account to read every lesson, practise with the exercises and keep track of your progress.