Encapsulation is one of the main concepts in Object Oriented Programming(OOP). It is also called information hiding . An object has to provide its users only with the essential information for manipulation, without the internal details. For e.g. A Secretary using a Laptop only knows about its screen, keyboard and mouse.Everything else is hidden internally under the cover. She does not know about the inner workings of Laptop, because she doesn’t need to, and if she does, she might make a mess. Therefore parts of the properties and methods remain hidden to her.

Another e.g. will be Bluetooth which we usually have it in our mobile. When we switch on the Bluetooth I am able to connect another mobile but not able to access the other mobile features like dialing a number, accessing inbox etc. This is because,Bluetooth feature is given some level of abstraction.

If a data member is private it means it can only be accessed within the same class. No outside class can access private data member (variable) of other class. However we can hide private field implementation details inside the public method. Let’s see an example to understand this concept better.

public class Employee{
    private int _ssn;
    //Getter and Setter methods
    public int getEmployeeSSN(){
        return _ssn;
    public void setEmployeeSSN(int newSSN){
        _ssn = newSSN;

public class Test{
    public static void main(String args[]){
         Employee emp = new Employee();
           System.out.println("Employee SSN: " + emp.getEmpSSN());

In above example the data member (or data field) is private which cannot be accessed directly. These fields can only be accessed via public methods only (getEmployeeSSN).

The biggest advantage of encapsulation is 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.

3 thoughts on “What is Encapsulation?

  1. I will try to write this code and see how exactly it behaves but sounds like you have already covered all the base.
    Big thumbs up!!!!

Leave a Reply

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