Encapsulation

The field is private, the behaviour is a method.

A private field is visible only inside the class. From the outside there is a method. This is not secrecy for its own sake. It is where a rule lives: an age is never negative, a list is not handed out as a live reference, a name is not overwritten with spaces.

A getter that simply returns a field makes sense when the field must not be changed from outside. A setter for every field with no rule behind it is a public field with extra noise. If the object does not change after the constructor, you do not need a setter at all.

Do not return the internal ArrayList directly if the caller must not change it. Return a copy or an unmodifiable view. Otherwise someone else's code will call list.clear(), and your object falls apart without a single call to your methods.

In the task, a box holds a number and hands it out through the get method. Nobody reads the field from outside. Later a database connection is hidden the same way: outside there is a findUser method, inside a driver detail.

Practice

  1. Why private

    Why hide a field if a getter returns it anyway?

    • So that the value cannot be read
    • So that the rule lives in one place
    • So that the class becomes static
    • So that you do not have to write a constructor
  2. The method's name

    The field is hidden. In this task, what is the method that returns the number called? One word.

  3. A hidden number

    Make a class with a private number. The constructor takes 7, the get method returns it. Print the result of get.