Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit. In encapsulation the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class, therefoe it is also known as data hiding.
To achieve encapsulation in Java
- Declare the variable of a class as private
- Provide public setter and getter methods to modify and view the variables values.
Encapsulation is used to reduce dependencies, so if you want to change something you can change it and it won't affect other classes because it was encapsulated and it only affects that class.
Example:
Source: Encapsulation
Thxcank you so much for this. I was into this issue and tired to tinker around to check if its possible but couldnt get it done. Now that i have seen the way you did it, thanks guys
with
regards
https://akinator.ooo/, Jul 06 2019 on venkonprogram.withknown.com