Encapsulation in Java

Object-Oriented Programming is totally based on four major pillars InheritanceAbstraction, Encapsulation, and Polymorphism. A professional java developer must have knowledge of these pillars. In this post, we will give you complete knowledge of one of the most important concepts of OOPs i.e. Encapsulation in Java. How to achieve encapsulation in oop and how does work encapsulation in java with real time example.
Here is the table content of the article will we will cover this topic.
1. What is Encapsulation in Java?
2. Rules for encapsulation in Java?
3. Advantages of Encapsulation in Java?

What is Encapsulation in Java?

Let’s define encapsulation in java or data encapsulation in oops:
Encapsulation is a process in which data and action bind together. In Java, using encapsulation when data and function are enclosed. By the use of encapsulation, data and function can wrap together in a single unit.
The encapsulation is a shield that protects the data and prevents it from being accessed by the code outside the shield.

We can create a fully encapsulated class in Java by making all the data members of the class private. In encapsulation, the variables of a class are not accessible from outside the class. Because they are hidden in other classes. These variables can access only by the methods in which declared in the same class. Therefore, it is also known as data hiding.

Encapsulation in Java

In encapsulation, the variables of a class are hidden from any other class. We can protect them by declaring all the variables as private. The private variables are only accessible through the method, so we declared the method as public. If any class wants to interact with class variables, then there is only one way to interact which is a public method. Encapsulation is achieved by making the variables of the class private and the class exposed to the end-user in the abstract concept. We will explain it by diagram and after that discuss it in detail.

Encapsulation Java Private Variable

It is used to hide the internal representation from outside the class. You can protect the state of an object. Let’s say if we implemented encapsulation in a class then an attribute that is not visible from the outside of an object and no one can change its state without the read and write access.

How to achieve encapsulation?

We can achieve encapsulation in java, we need to follow some rules and syntax. Whenever you are creating a class POJO(Plain old java object) class? Then you have to declare variables with private keyword and methods with the public keyword.

class <class_name>
{
    private variableName; // To achieve encapsulation variables should be private
     //Getter and Setter methods
    public returntype methodName(){
	// Methods should be public 
    }
    public void methodName(dataType variableName)
    {
       // Methods should be public 
    } 
}
class Student
{
   // For encapsulation all variables should be private
    private int rollNo;
    private String name;
    private String className;

    //You should provide setter ad getters for variables
public int getRollNo (){
        return rollNo;    }
public String getName(){
        return name;      }
public String getClassName(){
        return className;   }
 public void setRollNo (int value){
        rollNo = value;    }
 public void setName (String value){
        name = value;     }
public void setClassName (String value){
        className = value;
    }
}
public class EncapsulationExample
{
    public static void main(String args[])
    {
         Student obj = new Student();
         obj. setRollNo (1);
         obj. setName ("RAVI");
         obj. setClassName ("MCA");
         System.out.println("Student RollNo: " + obj.getRollNo ());
         System.out.println("Student Name: " + obj.getName ());
         System.out.println("Student Class: " + obj.getClassName ());
    } 
}

Output: Student RollNo: 1
Student Name: RAVI
Student Class: MCA

Rules for encapsulation in Java

1. Variable of a class should be declared as private
2. To access the values of the variables, create public setter and getter methods.

Advantage of Encapsulation in Java

1. It gives better maintainability and flexibility and re-usability

Let’s discuss the above example. If you are changing in variable name or value, then other classes will not affect this change. They can be still simply accessing the setter and getter. We can it at any point in time. This is introducing maintained property because we can change it without breaking classes.

2. read-only mode

If we don’t provide setter methods in the class, then the variable will be read-only. If we don’t want to change the value of any variable, then we will not provide its setter method.

Example :

  • First, we need to declare it a private keyword.
  • Don’t declare any setter method for that variable which you wouldn’t be changed.
  • Since the set method is not present, so there is no way an outside class can modify the value of that field.
//This Java class which has only getter methods. It provides ready-only mode  
public class StudentKnowledge
{  
       //private variables
       private String knowledgeSource="JAVACONCEPTDOOR";  
      //getter method for knowledgeSource
      public String getKnowledgeSource()
     {  
       return knowledgeSource;  
      }
}
StudentKnowledge s = new StudentKnowledge();
s. setKnowledgeSource("ABC");//will render compile time error  

Explanation: Now, you can’t change the value of the knowledge source data member that is “JAVACONCEPTDOOR”. There is no setter method declared, so you can’t change its value from outside the class.

3. write-only mode

If we don’t provide getter methods in the class then the variable will be write-only(). If you don’t want to give access to the variable from outside the class? Then we will not provide its getter method.

Example :

  • First, we need to declare it a private keyword.
  • Don’t declare any getter method for that variable.
  • Since the get method is not present, so there is no way an outside class can modify the value of that field.

Example of Read-only:

//This Java class which has only setter methods. It provides write-only public class StudentExample
{  
   //private variables  
   private String knowledgeSource;  
   //setter method for knowledge 
   public void setKnowledgeSource (String knowledge)
  {  
       this. knowledgeSource = knowledgeSource;  
   }  
}  
System.out.println(s.getKnowledgeSource());//Compile Time Error, because there is no such method  
System.out.println(s.knowledgeSource);//Compile Time Error 

Explanation: Now, you can’t get the value of the knowledge because the college data member is private.  So, it can’t be accessed from outside the class. You can only change the value of the knowledge data members.

1 thought on “Encapsulation in Java”

Leave a Comment