Facebook Page Twitter Page LinkedIn Page
× Java Tutorial Java Advanced Java Resources


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 below example, 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.

/* File name: Circle.java */
  public class Circle {
    //class attribute
    private int radius = 10;
  }

/* File name: RunCircle.java */
  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 below example, public set and get methods are created to access private member radius of class Circle.

/* File name: Circle.java */
  public 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;
    }
  }

/* File name: RunCircle.java */
  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