What is Encapsulation?

Purpose of Encapsulation:

  • Protects the code from others.
  • Code maintainability.

Example: 

We are declaring ‘a’ as an integer variable and it should not be negative.

public class{
    int a=5; 
}

If someone changes the exact variable as “a = -5” then it is bad.

In order to overcome the problem, we need to follow the below steps:

  • We can make the variable as private or protected one.
  • Use public accessor methods such as set<property> and get<property>.

So that the above code can be modified as:

public class Addition{
    private int a = 5; //Here the variable is marked as private
}

Below code shows the getter and setter.

Conditions can be provided while setting the variable.

get A{

} 
set A(int a){ 
    if(a>0){
    // Here condition is applied 
    }
}

We need to render all the instance variables as private for encapsulation and build setter and getter for those variables. Which in effect will cause others to call the setters instead of directly accessing the data.

Top 50+ Java Interview Questions with Answers

We covered nearly 50 + primary Java interview questions in this tutorial for fresh and experienced candidates.  Q.1- What is… Read More

5 years ago