This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
The code example had default access to variable x which means every class in the same package can access it directly. The description is correct, but the code would not have been considered tightly encapsulated.
Encapsulation is a form of data hiding, intended to protect data from external corruption. A tightly encapsulated class prevents direct public access to fields by making them private.
These field values might be returned or modified by public "accessor" and "mutator" methods, although these methods are not required for encapsulation. (Note that accessor methods are typically named "get...," while mutator methods are typically named "set..."). To help protect data, mutator methods can impose constraints on argument values, and throw IllegalArgumentExceptions.
If a class is not tightly encapsulated, then none of its subclasses are. A class that returns a reference to an internal, mutable object is not tightly encapsulated. However, a tightly encapsulated class may return a reference to an immutable object, or to a copy or clone of an internal object.
Encapsulation makes code easier to maintain by allowing changes to the data structure without changes to the public interface. [ November 04, 2004: Message edited by: marc weber ]
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org
Joined: Nov 01, 2004
Thanks everybody for providing the information and thanks Marc for such a detailed information about the tightly encapsulated classes.