Encapsulation is one of the fundamental concept of object-oriented programming (OOP) It is widely used for data hiding, it binds the data (variables) and the methods (functions) in a single unit called class. In this guide, we will learn this concept with the help of examples and programs.
Note: If you are looking for a real-life example of encapsulation then refer this guide: OOPs features explained using real-life examples.
For other OOPs topics such as inheritance and polymorphism, refer OOPs concepts
Lets get back to the topic.
What is encapsulation?
The whole idea behind encapsulation is to hide the implementation details from users. If a data member is private it means it can only be accessed within the same class. No outside class can access private data member (variable) of other class.
However if we setup public getter and setter methods to update (for example void setSSN(int ssn)
)and read (for example int getSSN()
) the private data fields then the outside class can access those private data fields via public methods.
This way data can only be accessed by public methods thus making the private fields and their implementation hidden for outside classes. That’s why encapsulation is known as data hiding. Lets see an example to understand this concept better.
Key Concepts of Encapsulation in Java:
- Private Variables: Instance variables of a class are marked as
private
to prevent direct access from outside the class. - Public Methods: Public getter and setter methods are provided to allow limited access to private variables.
- Data Hiding: When we make the data private, we hide how the object’s details are stored and managed from outside the object. Only the methods of the class can directly change or use the data
Example of Encapsulation in Java
How to implement encapsulation in java:
1) Make the instance variables private so that they cannot be accessed directly from outside the class. You can only set and get values of these variables through the methods of the class.
2) Have getter and setter methods in the class to set and get the values of the fields.
class EncapsulationDemo{
// Private variables (data hiding)
private int ssn;
private String empName;
private int empAge;
//Getter and Setter methods
public int getEmpSSN(){
return ssn;
}
public String getEmpName(){
return empName;
}
public int getEmpAge(){
return empAge;
}
public void setEmpAge(int newValue){
empAge = newValue;
}
public void setEmpName(String newValue){
empName = newValue;
}
public void setEmpSSN(int newValue){
ssn = newValue;
}
}
public class EncapsTest{
public static void main(String args[]){
EncapsulationDemo obj = new EncapsulationDemo();
obj.setEmpName("Mario");
obj.setEmpAge(32);
obj.setEmpSSN(112233);
System.out.println("Employee Name: " + obj.getEmpName());
System.out.println("Employee SSN: " + obj.getEmpSSN());
System.out.println("Employee Age: " + obj.getEmpAge());
}
}
Output:
Employee Name: Mario Employee SSN: 112233 Employee Age: 32
In above example all the three variables (or data fields) are private(see: Access Modifiers in Java) which cannot be accessed directly. These fields can be accessed via public methods only. Variables empName
, ssn
and empAge
are made hidden data fields using encapsulation technique of OOPs.
Advantages of encapsulation
1. It improves maintainability and flexibility and re-usability. For example, in the above code the implementation code of setEmpName(String name)
and String getEmpName()
can be changed at any point of time.
Since the implementation is purely hidden for outside classes they would still be accessing the private field empName using the same methods (setEmpName(String name)
and getEmpName()
).
Hence the code can be maintained at any point of time without breaking the classes that uses the code. This improves the re-usability of the underlying class.
2. The fields can be made read-only (If we don’t define setter methods in the class) or write-only (If we don’t define the getter methods in the class).
For example, if we have a field(or variable) that we don’t want to be changed so we simply define the variable as private and instead of set and get both we just need to define the get method for that variable. Since the set method is not present there is no way an outside class can modify the value of that field.
3. User would not be knowing what is going on behind the scene. They would only be knowing that to update a field call set method and to read a field call get method but what these set and get methods are doing is purely hidden from them.
Encapsulation is also known as “data Hiding“.
sowrag says
i am confused about when doGet() and doPost() methods are used ,plz could u clarify my doubt
Ather says
We use doPost() method when we dont want the data(while submitting a form) to be send through the URL while in doGet() form data is sent though URL
Asiri says
i am really confused, in java we cannot have two public methods in a same source file. one method should only be public.
Chaitanya Singh says
@Asiri, No we can have any number of public methods in a class. We cannot have more than one public class in the same source file.
Anish says
doGet() vs doPost() methods are used to change implementation of form, such as doGet() method exposed the all form submitting data into URL bar at page run time.and doPost() method not exposed form data in url bar at run time its more secureful……its my according….
shyamal says
Thanks for very good post
Anonymous says
Hi,
Thanks for this post. This is really good and easy to understand. But, can you please explain this with a real time scenarios. because this is easy to understand but how practically this is useful. And where exactly this is needed.
Thanks.
anitha says
Hi
I can understand the concept of encapsulation and program. But how could u say that. It hide the data but we can use the function. And I have a doubt is so that without using get and set method we can’t achieve encapsulation.
Harsha vardhan says
public class Encapsulation1{
public static void main(String args[]){
Encapsulation obj = new Encapsulation();
obj.setEmpName(“Mario”);
obj.setEmpAge(32);
obj.setEmpSSN(112233);
System.out.println(“Employee Name: ” + obj.getEmpName());
System.out.println(“Employee SSN: ” + obj.getEmpSSN());
System.out.println(“Employee Age: ” + obj.getEmpAge());
}
When i am executing above code.the following error has been occurring.Help me to solve this error …This is Error i am getting.
The public type Encapsulation1 must be defined in its own file
sachin says
Encapsulation obj = new Encapsulation(); //is error
Encapsulation1 obj = new Encapsulation1(); //rectified
Save the file name as Encapsulation1.java
Rshan says
you can not use the key word encapsulation..
so you can rename it with any other name….
Randy Dickinson says
very good explanation of encapsulation and how and why it works nice job
aditya raghuwanshi says
what is the difference between abstraction and encapsulation while they both are hiding the implementation from user.plz answer me.
Ranjeet Singh says
“Abstraction is implemented using interface and abstract class while Encapsulation is implemented using private and protected access modifier.”
DKL says
Abstraction identifies which information should be visible as well as which information should be hidden. Encapsulation packages the information in such a way as to hide what should be hidden, and make visible what is intended to be visible. I hope that helps.
kiran M Patel says
we use abstraction when we are not sure about certain implementation.
for e.g -> car surely need fuel but may or maynot need ac & wiper features.
so we define implementation for only fuel() and make ac(),wiper()as abstract.i.e no implementation.
encapsulation-> provides data protection/hiding.
->Technically in encapsulation, the variables or data of a class is hidden from any other class and can be accessed only through any member function of own class in which they are declared.
-> Encapsulation can be achieved by: Declaring all the variables in the class as private and writing public methods in the class to set and get the values of variables.
janardhan says
can you please explain the difference between the terms–> Bean,POJO,JavaBean,EJB,Entity,DataTransferObject,springBean–
ravi says
can you please explain the difference between the private public an protected and encapsulation inheritance and polymorphism with simple examples?
rajeshkumar says
@Ravi… Hi, for Public modifier we can access the methods or varibles from another class to another class. But when we going for Private Modifier we can’t access from another class but we can access within the class.
Inheritance: There is a class called Class A and Class B. We can use the Class A methods in Class B by using the extends Keyword. For eg. public class classA
{public static void add(){…}
}
public class classB extends class A
{
public static Void sub(){…}
public static void main(String[] args){ add();sub()}}
Ankit says
Very nice article.
One question:
Within a single file 2 (two) public class is possible ?
As per my knowledge only one public class we can declare .
Krupen Ghetiya says
To make variables read-only, you can also declare them as “final” and set them in constructor, making them private is not the only way :) .
Parnika says
Nice tutorial for beginners.
I have a doubt in Encapsulation which confuses us all the time. Encapsulation means Data hiding, for that we are declaring data members so that outside class cannot access.[Security purpose].
But here when other classes can access those values through setter and getters methods, then where is security lies here. Why to hide data with private specifier and why to access with setter and getter methods?
Chaitanya Singh says
The main difference between making a data member public vs. accessing it using getter setter methods is taking the control over the data members.
By making a field public, you are allowing the direct access. This way anyone can change the value of the field without any validation, for example anyone can set a data member to null, even if it is not supposed to be null. You have no control here.
The same thing when you do with the help of setter method then you can have a validation check in the setter method itself to not set the value of the field if it is supplied as null.
Hope this helps.