Java Tutorial

OOPS concept


Java Encapsulation

Encapsulation is the process of wrapping of data i.e. variables and code that acts on data i.e. methods in a single unit.

In encapsulation the variables are kept private and can only be accessed by the methods. Now here the data members are kept hidden from other classes therefore it is known as data hiding. The private data can be accessed by using getter and setter methods.

Why Encapsulation?

1. It allows us to make any field read-only or write-only. For this we have to use only getter and setter.
2. We will have control over the stored value in a field.


Here is a very simple example for encapsulation.

class Employee{
private String name;
private int id;

public String getName(){
return name;

public int getId(){
return id;

public void setName(String name)
{ = name;

public void setId(int id)
{ = id;

Above class is class made for an employee. We have two private variables name and id. There are methods for getter and setter so that variables can be accessed from outside the class. Below class is uses Employee class and sets name and id for an employee. After that it is getting the data to display using getter methods.

class Main{
public static void main(String args[]){

Employee emp = new Employee();

//Set Data

//Get data
System.out.println("Name: "+emp.getName());
System.out.println("Id: "+emp.getId());