Java Tutorial Java Advanced Java References

Java - Encapsulation



Access Specifier

Before understanding the concept of encapsulation, it is important to understand the concept of access specifier. Access specifiers defines the access type of the attributes and methods of the class and there are four types of access specifier in Java.

  • public: Attributes and methods of the class are accessible from everywhere.
  • protected: Attributes and methods of the class are accessible within the package or all subclasses.
  • private: Attributes and methods of the class are accessible within the class only.
  • default (when no access specifier is specified): Attributes and methods of the class are accessible only within the package (package private).

Example:

In the example below, a class called Circle is created which has a private attribute called radius. When it is accessed in another class called RunCircle, it raises an exception because it is a private attribute and it can not be accessed outside the class in which it is defined.

class Circle {
  //class attribute
  private int radius = 10;
}

public class RunCircle {
  public static void main(String[] args) {
    Circle MyCircle = new Circle();

    System.out.println(MyCircle.radius);
  }
}

The output of the above code will be:

RunCircle.java:12: error: radius has private access in Circle
    System.out.println(MyCircle.radius);

Encapsulation

Encapsulation is a process of binding the attributes and methods together in a single unit called class. It is aimed to prevent the direct access of attributes and available only through methods of the class. Data encapsulation led to the important concept of data hiding in object-oriented programming also known as Data abstraction. Data abstraction is a mechanism of exposing only the interfaces and hiding the implementation details from the user.

Data Encapsulation steps:

  • Declare each attribute private.
  • Create public set method for each attribute to set the values of attributes.
  • Create public get method for each attribute to get the values of attributes.

In the example below, public set and get methods are created to access private member radius of class Circle.

class Circle {
  //class attribute
  private int radius;
  //method to set the value of radius
  public void setRadius(int x) {
    radius = x;
  }
  //method to get the value of radius
  public int getRadius() {
    return radius;
  }
}

public class RunCircle {
  public static void main(String[] args) {
    Circle MyCircle = new Circle();
    
    //set the radius
    MyCircle.setRadius(50);
    //get the radius
    System.out.println(MyCircle.getRadius());
  }
}

The output of the above code will be:

50