I am learning Java and have been given these options:
How can you implement encapsulation in a class?
- Make all variables protected and only allow access via methods.
- Make all variables private and only allow access via methods.
- Ensure all variables are represented by wrapper classes.
- Ensure all variables are accessed through methods in an ancestor class.
My choice is the second but I also would like to find out if anyone considers any other choice is correct? Also are there any other ways to implement encapsulation that are not covered here?
You’re right.
Any other method is to define an interface which will be encapsulate functionality of implementation class.
from Wikipedia:
encapsulation is: