Encapsulation in Java

Encapsulation in java is a mechanism of binding all data (fields) and the methods to manipulating data together into a single Class. Encapsulation is one of the four fundamental object oriented programming concepts.

The data of a class will be hidden from external classes, it is not directly accessible by external code. It can only be accessed through public methods of their class.

Encapsulation provides the security by hiding the internal data and implementation details from external code to avoid inadvertent changes. By calling public methods of a class, any external entity can access the data but cannot modify it.

Advantages of Encapsulation
  • Hiding the critical data from external components by making them private. Class have full control over what is stored and how, also how to expose the data to external world.

  • Hiding implementation details from clients. Rest of the world know how to access this information without knowing how it is calculated or managed.

  • We can change the data and internal implementation any time without affecting any client..as long as the we are not changing the interface of public methods.

How to achieve encapsulation in Java

  • Declare the member variables of class as private.

  • Expose some public methods for external world to interact with your class.

  • Keep you implementation details hidden inside private methods.

Java program for encapsulation

class Rectangle {
  // private data
  private int length, width;

  public void setLength(int length) {
    this.length = length;

  public void setWidth(int width) {
    this.width = width;
  public int calculateArea() {
    return length * width;
public class EncapsulationJava {
  public static void main(String[] args) {
    Rectangle rect = new Rectangle();
    // Invoke public methods
    System.out.println("Area = " + rect.calculateArea());
Area = 200

In the above program, we have created a class called Rectangle, which provides a public method to calculate area of rectangle. Member variable length and width are declared with private modifier. Hence, they cannot be accessed from outside.

The public method setLength() and setWidth() are the only access points of the instance variables of the Rectangle class. Any class that wants to access the variables should access them through these getters methods. Making length and width fields private allowed us to restrict unauthorized access from outside the class.