Purpose of Encapsulation:
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:
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.
We covered nearly 50 + primary Java interview questions in this tutorial for fresh and experienced candidates. Q.1- What is… Read More