Posted on Leave a comment

Design Principle: Encapsulation – Access Control

6.1 Design Principle: Encapsulation

An object has properties and behaviors that are encapsulated inside the object. The services that the object offers to its clients make up its contract, or public interface. Only the contract defined by the object is available to the clients. The implementation of the object’s properties and behavior is not a concern of the clients. Encapsulation helps to make clear the distinction between an object’s contract and its implementation. This demarcation has major consequences for program development, as the implementation of an object can change without affecting the clients. Encapsulation also reduces complexity, as the internals of an object are hidden from the clients, which cannot alter its implementation.

Encapsulation is achieved through information hiding, by making judicious use of language features provided for this purpose. Information hiding in Java can be achieved at the following levels of granularity:

  • Method or block declaration

Localizing information in a method or a block hides it from the outside. Local variables can only be accessed in the method or the block according to their scope.

  • Reference type declaration

The accessibility of members declared in a reference type declaration (class, enum type, interface) can be controlled through access modifiers (p. 347). One much-advocated information-hiding practice is to prevent clients from having direct access to data maintained by an object. The fields of the object are private, and the object’s contract defines public methods for the services provided by the object. Such tight encapsulation helps to separate the use from the implementation of a reference type.

  • Package declaration

Top-level reference types that belong together can be grouped into relevant packages by using the package statement. An import statement can be used to access types in other packages by their simple name. Inter-package accessibility of types can be controlled through public or package accessibility (p. 345).

  • Module declaration

Packages that are related can be grouped into a module by using a module declaration. How modules are created, accessed, compiled, and deployed is discussed in detail in Chapter 19, p. 1161.

Ample examples throughout the book illustrate how encapsulation can be achieved at different levels by using features provided by the Java programming language.

Leave a Reply

Your email address will not be published. Required fields are marked *