Tutorials

Java Object Oriented Programming


Encapsulation


The process of wrapping up of data (e.g., variables) and function (or methods) into single unit called class is defined as encapsulation.
Encapsulation gives power to hide variable of a class from other classes. The variable can be accessed only through the methods of the class whose variable other class wants to access.
 
For the same reason, encapsulation is also known as data hiding.

 

How to achieve encapsulation in java?

  • Variable that you need to hide should be declared private.
  • Create public getter and setter methods that can only modify the variable or view the variable.
 
Example: Getter-Setter example

	
package calculator;

public class CalculatorVO {

      private int firstNumber;
      private int secondNumber;

      public int getFirstNumber() {
            return firstNumber;
      }

      public void setFirstNumber(int firstNumber) {
            this.firstNumber = firstNumber;
      }

      public int getSecondNumber() {
            return secondNumber;
      }

      public void setSecondNumber(int secondNumber) {
            this.secondNumber = secondNumber;
      }

}

Advantage of Encapsulation

  • Using encapsulation helps us to make our variable read only or write only. For example we have declared our variables firstNumber and secondNumber private. To make these variables read only we can reove the setter methods for both of them. To make it write only, we can remove the getter method. This in turn provide programming flexibility.
  • Encapsulation also helps in data hiding. For instance, in our above code snippet, variables firstNumber and secondNumber is private and thus hidden from outside world. No one can access them directly. The only mean to access them is though their getter and setter method.
  • Encapsulated code is easy to test and maintain.


Please Share this page
Views : 136
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!