Encapsulation in Java

Encapsulation is the mechanism for restricting access to an object’s components. It aims for high maintenance and handling of the application’s code. Also, the encapsulation mechanism protects the members of a class from external access, in order to be protected against unauthorized access.

Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed by other code defined outside the class. Also, encapsulation provides the ability to modify our implemented code without breaking the code of others who use our code. Thus, using encapsulation we can achieve maintainability, flexibility, and extensibility of our code.

Java provides three keywords in order to define the scope and the access permissions of a class member or method: public, private and protected. A public member or method can be accessed from any other class. A private member or method is accessible only within its own class. Finally, a protected member is accessible within its class, its sub-classes and in all classes that reside in the same package.

Design Patterns and Encapsulation

The encapsulation mechanism is used by very popular design patterns, in order to provide a specific functionality. For example, the Factory Pattern aims for creating objects, without exposing the implementation logic to the client. On the other hand, the Singleton Pattern is used to ensure that at most one instance of a class will be created. Both these patterns are based on the encapsulation, in order to implement their functionality.

Final comments about Encapsulation

As we already mentioned, the encapsulation mechanism aims for controlling the access to the fields or methods of a class and for providing flexibility. Specifically, by using encapsulation while coding our applications, we:

  • Combine the data of our application and its manipulation in one place.
  • Allow the state of an object to be accessed and modified through behaviors.
  • Hide the implementation details of an object.
  • Reduce the coupling of modules and increase the cohesion inside them.
  • Create immutable classes that can be used in multi-threaded environments.

Finally, we must not confuse the encapsulation mechanism with the abstraction mechanism: the latter aims to specify what an object can do, while the former aims to specify how an object implements its functionality.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s