Java – Encapsulation

Access Specifier

It is necessary to comprehend the notion of access specifier before understanding the concept of Java – Encapsulation. The access type of a class’s properties and methods is defined by access specifiers, and there are four types of access specifiers in Java.

  • public: The class’s attributes and methods are available from everywhere.

 

  • protected:  Class’s attributes and methods are available from inside the package or all subclasses.

 

  • private: The class’s attributes and methods are only available within the class.

 

  • default (when no access specifier is specified): When no access specifier is supplied, the class’s attributes and methods are only available within the package (package private).

A class called Circle is constructed in the example below, and it contains a private attribute called the radius. It generates an exception when it is accessed in another class named RunCircle because it is a private attribute that can only be accessed within the class in which it is declared.

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

Java – Encapsulation is the process of combining properties and methods into a single unit known as a class. Its purpose is to block direct access to attributes and make them available only through the class’s methods. Data encapsulation led to the essential notion of data hiding, also known as Data abstraction, in object-oriented programming. The abstraction is a method of providing only the interfaces to the user while obscuring the implementation details. Lets us know the steps of Java – Encapsulation.

Data Encapsulation steps:

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

To access the private member radius of class Circle, public set and get methods are developed in the example below.

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:

Encapsulate Crawlspace

Leave a Reply

Your email address will not be published.