Encapsulation in Java2 min read

What is Encapsulation in Java

Encapsulation in Java means that a class’s variables are concealed from other classes and can only be accessed through its current class’s methods. One of the four core OOP ideas is encapsulation. Inheritance, polymorphism, and abstraction are the other three.

  • Encapsulation is the process of making a class’s fields private but allowing public methods to access them.
  • When a field is designated private, it can’t be accessed by anyone outside of the class, thereby obscuring the class’s fields.
  • Encapsulation is often known as data concealing because of this.
  • Encapsulation is a protective barrier that stops other codes declared outside the class from accessing the code and data at random.
  • An interface tightly controls access to the data and code.
  • The ability to modify our implemented code without damaging the code of those who utilize our code is the major benefit of encapsulation.


//A Java class which is a fully encapsulated class.  
//It has a private data member and getter and setter methods.  
package hiberstack;  
public class Student{  
  //private data member  
  private String name;  
  //getter method for name  
  public String getName(){  
    return name;  
  //setter method for name  
  public void setName(String name){  
    this.name = name;
//A Java class to test the encapsulated class.  
package hiberstack;  
class Test{  
  public static void main(String[] args){  
    //creating instance of the encapsulated class  
    Student s=new Student();  
    //setting value in the name member  
    //getting value of the name member  



Benefits of Encapsulation

  • A class’s fields can be set to be read-only or write-only.
  • Anything stored in a class’s fields can be completely controlled by the class.
  • A class’s users are unaware of how the class saves its data.
  • A class can change the data type of a field without requiring its users to update their code.
  • Data Hiding The user will be unaware of the class’s inner workings. The user will not be able to see how the class stores values in variables. Only the user will be aware that the values are being passed to a setter method and that variables are being initialized with that value.
  • Testing Unit testing is simple with encapsulated code.
  • Code Reusability Encapsulation also promotes reusability and makes it simple to adapt to changing requirements.
  • Increased Flexibility – It gives you complete control over your data. You can write the logic inside the setter method if you want to set the value of id to be greater than 100 only. You can implement logic in the setter methods to prevent negative integers from being stored.


Leave a Reply