Implementing Encapsulation In Java

Hi Guys, after long break…Today we will discuss one of the most important concept ‘Encapsulation‘ It’s quite difficult to understand the concept of encapsulation from a definition. So let’s understand what encapsulation is by looking at some code examples.Basically, there are two forms of encapsulation in OOP.

First, encapsulation is a technique that packages related data and behaviors into a single unit.

Let’s see an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Person{
    String name;
    intage;
    
    voidtalk() {
    }
    
    voidthink() {
    }
    
    voidwork() {
    }
    
    voidplay() {
    }
}

Advantages of encapsulation:

  1. It improves maintainability and flexibility and re-usability: for e.g. In the above code the implementation code of void setEmpName(String name)and String getEmpName() can be changed at any point of time. Since the implementation is purely hidden for outside classes they would still be accessing the private field empName using the same methods (setEmpName(String name) and getEmpName()). Hence the code can be maintained at any point of time without breaking the classes that uses the code. This improves the re-usability of the underlying class.
  2. The fields can be made read-only (If we don’t define setter methods in the class) or write-only (If we don’t define the getter methods in the class). For e.g. If we have a field(or variable) which doesn’t need to change at any cost then we simply define the variable as private and instead of set and get both we just need to define the get method for that variable. Since the set method is not present there is no way an outside class can modify the value of that field.
  3. User would not be knowing what is going on behind the scene. They would only be knowing that to update a field call set method and to read a field call get method but what these set and get methods are doing is purely hidden from them.

Encapsulation is also known as “data Hiding”.

  1. Objects encapsulate data and implementation details. To the outside world, an object is a black box that exhibits a certain behavior.
  2. The behavior of this object is what which is useful for the external world or other objects.
  3. An object exposes its behavior by means of public methods or functions.
  4. The set of functions an object exposes to other objects or external world acts as the interface of the object.

Leave a Reply

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