9.4. Private Object State and Object Immutability

Most objects have private, internal states that should not be randomly modified. Often, other objects need to query the state information. Many programmers implement a query method by using a simple return statement, as in the following example:

public MyClass {
   private boolean status = false;

   public void setStatus(boolean s) {
      status = s;
   }

   public boolean getStatus() {
      return status;
   }
}

No problem so far. However, if status is not a simple boolean but rather an array of boolean, serious problems can occur, as here:

public MyClass {
   private boolean[] status = null;
   . . .
   public boolean[] getStatus() {
      return status;
   }
}

In this example, once it obtains a reference to the private status

Get Inside Java™ 2 Platform Security: Architecture, API Design, and Implementation, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.