ENCAPSULATION IN JAVA


Encapsulation In JAVA | Core Java Tutorial | Minigranth

Encapsulation in Java : Introduction

  • Encapsulation in java is one of the most important concept of object oriented programming. We have already discussed a way to achieve encapsulation by using packages.
  • The wrapping up of fields and methods into a single unit is called encapsulation. In Java everything is encapsulated in a class.
  • We can create an encapsulated class by declaring all the data fields (variables) as private. We have to provide getter and setter methods to view and access variables.
    1. The Getter Method
      • Getter method is used to retrieve and view private variables values.
    2. The Setter Method
      • Setter method is used to access or update private variables values.

Encapsulation In Java : Example

  • Let us discuss an example of encapsulation.

  • This image describes the program supporting the concept of encapsulation in java.
    Encapsulation In Java : Example

    This image describes the output of program supporting the concept of encapsulation in java.
    Encapsulation In Java : Output

  • Advantages of implementing encapsulation is that it protect the application from external access.
  • No external factor can access the private fields of an encapsulated class. It can only be done using getter and setter methods.