Table of Contents
Encapsulation
in java is the process of binding related data(variables) and functionality(methods) into a single unit called class. Encapsulation can be achieved by using access modifier such as public, private, protected or default, so your class will be safe from unauthorized access by others and will be simple to maintain.
We can create fully encapsulated class by
- Making variables private
- Providing getters and setters methods for the accessing the variables.
Encapsulation is also termed as data hiding
 because you are making variables private and variables can be only accessed through public getters and setters.
Example of Encapsulation in java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
package com.arpit.java2blog; public class Employee{ private int employeeId; private String employeeName; private String department; public int getEmployeeId() { return employeeId; } public void setEmployeeId(int employeeId) { this.employeeId = employeeId; } public String getEmployeeName() { return employeeName; } public void setEmployeeName(String employeeName) { this.employeeName = employeeName; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public static void main(String args[]) { Employee e1=new Employee(); e1.setEmployeeId(1); e1.setEmployeeName("John"); e1.setDepartment("Sales"); System.out.println("============="); System.out.println("Employee Id: "+e1.getEmployeeId()); System.out.println("Employee Name: "+e1.getEmployeeName()); System.out.println("Employee Department: "+e1.getDepartment()); } } |
When you run above program, you will get below output:
Employee Id: 1
Employee Name: John
Employee Department: Sales
Advantages of Encapsulation in java:
- It provides control over data. For example:Â If You want to check if age of employee is greater than 18 in setter method(
setAge(int age)
). You can easily do it in setter method without breaking any code. - Increase reusability.
- Makes class easy to use for other clients.
- It helps the developer to write code more flexible and maintainable by binding them into a single unit and use appropriate access modifier to access the code as per need.
Difference between abstraction and encapsulation in java:
- Encapsulation means data hiding using getter and setters. Abstraction means hiding implementation details using [abstract class](https://java2blog.com/abstract-class-java/ “abstract class”) and [interface](https://java2blog.com/interface-in-java-with-example/ “interface”).
- Abstraction is more of design level concept and Encapsulation is more of implementation level concept.
That’s all about encapsulation in java.