OO Concepts – Encapsulation

One of the building blocks of OOP, Encapsulation can have either of 2 meanings (thanks, Wikipedia) :

1. “A language mechanism for restricting access to some of the object’s components.”
2. “A language construct that facilitates the bundling of data with the methods (or other functions) operating on that data.”

Information Hiding
Generally, when we talk about encapsulation in OOP we are talking about Information hiding – closely related to abstraction. As an example, we may want to get a value from an object without worrying about its internal representation.

Here is an example:

public class Person {
  private final String firstName;
  private final String lastName;
  public Person(final String firstName, final String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;

  public String getFullName() {
     return firstName + " " + lastName;

In this example we can get a full name for the person regardless of how the first and last names are stored internally inside the Person object. This is the OO version of encapsulation.

In a nutshell, we are protected from changes in the internal representation of data, it is hidden from clients of the Person class – hence the private modifier.

For an alternative take on encapsulation – storing data with the methods working on it – you can look here: http://www.javaworld.com/article/2075271/core-java/encapsulation-is-not-information-hiding.html


4 thoughts on “OO Concepts – Encapsulation

  1. Encapsulation can also help in making a robust design, we can move a very frequently changing API in our class to a seperate class/interface so that the original class is shielded from change.
    Encapsulation also help in Seperation of Concerns.

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 )


Connecting to %s