Java – Encapsulation

Encapsulation: Restricting direct access to object data and methods by using private access modifiers and providing public getters and setters.
Example:

class Employee {
private String name;
private int id;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getId() { return id; }
public void setId(int id) { this.id = id; }
}
Employee emp = new Employee();
emp.setName("John");
emp.setId(101);
System.out.println(emp.getName() + ", " + emp.getId());

No images available.