Java Reference
In-Depth Information
< Day Day Up >
Puzzle 73: Your Privates Are Showing
The idea behind private members— methods, fields, and types— is that they're simply
implementation details: The implementer of a class can feel free to add new ones and change or
remove old ones without fear of harming clients of the class. In other words, private members are
fully encapsulated by the class that contains them.
Unfortunately, there are a few chinks in the armor. For example, serialization can break this
encapsulation. Making a class serializable and accepting the default serialized form causes the
class's private instance fields to become part of its exported API [EJ Items 54, 55]. Changes in the
private representation can then lead to exceptions or erratic behavior when clients use existing
serialized objects.
But what about compile-time errors? Can you write a final "library" class and a "client" class, both
of which compile without error, and then add a private member to the library class so that it still
compiles but the client class no longer does?
Solution 73: Your Privates Are Showing
If your solution involves adding a private constructor to the library class to suppress the creation of
a default public constructor, give yourself half a point. The puzzle required you to add a private
member and, strictly speaking, constructors aren't members [JLS 6.4.3].
This puzzle has several solutions. One solution uses shadowing:
package library;
public final class Api {
 
 
Search WWH ::




Custom Search