Access modifiers are special keywords that define the accessibility or scope of a member. We can specify how other code can interact with specific methods or variables within or outside classes and packages. Like many programming concepts, access modifiers are simple in practice but can seem confusing at first. Once you understand them, they can help make your code more readable and maintainable.
Understand the Difference Between Members
Java provides 4 types of access modifiers with different scopes and visibility. Any member without any specifier is dealt with as “Default” or “package-private”.
- Private: A private member is accessible only in the same class
- Default (package-private): A member without any access modifiers is known as default or package private. Which is accessible in all classes of the same package
- Protected: A protected member is accessing all classes of the same package and subclasses of the other packages.
- Public: A public member is accessible all classes of all packages
See the below graphical representation, which will help you better outstanding about the scope of all members in different cases.
Hope this tutorial helped to under the difference between private, package-private (default), protected, and public members. Please put your valuable suggestions in the comment box.