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.
The Getter Method
- Getter method is used to retrieve and view private variables values.
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.
- 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.