exampracticeonline.com
Encapsulation

Encapsulation in Java

Encapsulation is one of the key concepts of OOPs in java. Encapsulation is a mechanism of binding code and data together into a single unit.

Pojo (Plain old java object) class is the Encapsulation example.

Let’s take an example of Capsule. Different medicines are encapsulated inside a capsule. Likewise in encapsulation, all the methods and variables are wrapped together in a single class.

4

How to achieve encapsulation in Java?

  1. Declare private variables in class.
  2. Provide public setter and getter methods to set the variables values and get the variables values.

Encapsulation example

We can create encapsulated class in java by making all data members private of class. These data members can access directly in same class if we want to access private data members outside the class we have to define public setter and getter methods of private data member.  

package com.jepo;

class EncapsulationDemo{

    private String empName;

    private int empAge;

    public void setEmpName(String empName){

        empName = this.empName;

    }

   public String getEmpName(){

        return empName;

    }

    public void setEmpAge(int empAge){

        empAge = this.empAge;

    }

    public int getEmpAge(){

        return empAge;

    }

}

public class EncapsulationTest{

    public static void main(String args[]){

         EncapsulationDemo obj = new EncapsulationDemo();

         obj.setEmpName("Smith");

         obj.setEmpAge(35);

         System.out.println("Employee Name: " + obj.getEmpName());

         System.out.println("Employee Age: " + obj.getEmpAge());

    }

}


Output:

Employee Name: Smith

Employee Age: 35


In above example all the two data members are private which cannot be accessed directly outside the class. These fields can be accessed via public methods only. Fields empName and empAge are made hidden data fields using encapsulation technique of OOPs.

Advantages of encapsulation

1. Data Hiding: The user will have no idea of inner implementation of encapsulated class. User can only set or get the private variable values by using public setter and getter methods.

2. Reusability: User can easily add or remove properties of class for future reference.

3. Easy Testing: Encapsulated code is easy to test for unit testing.

4. Increased Flexibility: We can make the variables of the class as read-only or write-only depending on our requirement. If we want to make read only then we can provide only public getter methods and if we want to make it write only then we can provide only public setter methods.