Encapsulation in Java

encapsulation

Encapsulation

Encapsulation in Java is a process of wrapping code and data together under a  single unit. In other words, we can say that it is a process of binding a code and the data that manipulates it under the same unit. It prevents external access to the data. If a data member is private it means it can only be accessed within the same class. No outside class can access private data members of other class.

It is also known as Data Hiding. To achieve encapsulation in Java −

  • Declare the variables of a class as private.

  • Provide public setter and getter methods to modify and view the values of the variables.

java encapsulation

By using encapsulation, data is only accessible through the functions present inside the class and the programmer cannot access the data directly. An example of a fully encapsulated class is the Java Bean. Let us understand the concept of encapsulation with the help of an example. Given below is a program to illustrate encapsulation.

Run
public class DemoEncapsulate 
{ 
    private int prepsterAge; 
    private String prepsterName; 
    private String prepsterCity;

public int getAge()
{
    return prepsterAge;
}

public String getName()
{
    return prepsterName;
}

public String getCity()
{
    return prepsterCity;
}

public void setAge( int newAge)
{
    prepsterAge = newAge;
}

public void setName(String newName)
{
    prepsterName = newName;
}

public void setCity(String newCity)
{
    prepsterCity = newCity;
}
}
  • In the program above, the class DemoEncapsulate is encapsulated, as the variables are declared as private.
  • The get methods like getAge() , getName() , getCity() are set as public, which will be used to access these variables.
  • The setter methods like setAge(), setName(), setCity() are also declared as public which are used to set the values of the variables.
Run
public class Main
{     
    public static void main (String[] args)  
    { 
        DemoEncapsulate obj = new DemoEncapsulate(); 
          
        obj.setAge(22);  
        obj.setName("Ashwin"); 
        obj.setCity("Meerut"); 
        
        System.out.println("Prepster's age: " + obj.getAge());
        System.out.println("Prepster's name: " + obj.getName()); 
        System.out.println("Prepster's city: " + obj.getCity()); 
          
              
    } 
} 

Output

Prepster's age: 22

Prepster's Name: Ashwin

Prepster's City: Meerut

Advantages of Encapsulation

  • Hidden Data: The user will have no idea about the inner implementation of the class and knows only that we are passing the values to a setter method and variables are getting initialized with that value.
  • Class attributes can be made read-only (if you only use the get method), or write-only (if you only use the set method)
  • Reusability: Encapsulation also improves the re-usability and easy to change with new requirements.
  • Testing code is easy: Encapsulated code is easy to test for unit testing.