|
While programming in Java, you frequently encounter a situation where you need to control the access to the code. As the important object-oriented principle, encapsulation[§§§§] suggests, the data and the internals of a class should be hidden and only the services the class provides should be accessible to everyone. To implement encapsulation, you need to have proper access control to ensure that the code is accessible only to the appropriate consumer objects. However, how you will specify who can and who cannot access a class and its members?
Java provides the access modifiers for restricting the access to a class and its members. The access is granulated into levels from most restrictive (private) to least restrictive (public). You can apply only one access modifier at a time. Say for example, a member variable declaration cannot have public and private modifiers at the same time. Let us see how you can use the three access modifiers to enforce the four kinds access restrictions.