Encapsulation in Java

This is one of most important principles of java. Encapsulation means binding of data into a single entity. It is a process of encasing the code and data to form one unit. To do this, you must make all data members of that class private.

Encapsulation is useful when the programmer or the client wants to hide information details or protect some data. It hides the fields within the class, and makes their access public.

If we look at class, we can see that it can have properties and operations, and in java properties mean variables and operations mean methods.

class A{
// variables a, b, c …
//methods m1 m2 m3….
}

In the above given example, class A is an entity which binds variables and methods. So we can conclude that java supports encapsulation by default.


Let's see, we have a class Student which has a property, age(i.e. variable )

Now functionally, can Student's age be negative? No, but we have allowed our clients to assign negative values.

He must not allow people to add age as a negative. Here, client 2 is correct but class Student is wrong functionally. So, it is rejected during the code review as per company standards, and the manager will say to person who designed class Student -“Hey, you have not encapsulated your class properly. People are putting invalid values. Please encapsulate properly.”

Here is how he changes the code:


In this case,

Client 2 :

Student s1=new Student ();
s1.age= - 45 // as age is private and therefore, not possible

  • Not possible as age is private

  • Client must go through method setAge(); in this method, the developer will send age not through variable but through the method where we put logic. Then, even if negative value is passed, the assigned value would be Zero, not negative. And that is ok

  • s1.setAge (-70); //s1.age= - 45 // in RAM, zero will always get stored

  • Now we can say that class Student is properly encapsula

  • Encapsulation is very important if we want to design classes properly as per functionality. What we learn here is to always keep global variables private, so that nobody can assign wrong values, or allow others to assign values through public methods.

To know encapsulation completely we must know access specifiers in detail.