What is the difference between protected, public, package-private, and private in Java?
What is the difference between protected, public, package-private, and private in Java?
460
21-Jul-2023
Updated on 22-Jul-2023
Aryan Kumar
22-Jul-2023Java has four access modifiers:
The access modifier of a class member (e.g., field, method, or constructor) determines whether the member is accessible to other classes.
Here's a table summarizing the difference between the four access modifiers:
Here are some examples of how to use the different access modifiers:
publicclass can be used by any class in any package.protectedclass can be used by subclasses of the class in which it is declared, and by classes in the same package.package-privateclass can be used by any class in the same package.privateclass can only be used by the class in which it is declared.Access modifiers can also be used on class members, such as fields, methods, and constructors. The access modifier of a class member determines whether the member is accessible to other classes.
For example, a
publicfield can be accessed by any class, while aprivatefield can only be accessed by the class in which it is declared.Here are some examples of how to use access modifiers on class members:
publicfield can be accessed by any class.protectedfield can be accessed by subclasses of the class in which it is declared, and by classes in the same package.package-privatefield can be accessed by any class in the same package.privatefield can only be accessed by the class in which it is declared.Access modifiers are an important part of Java's object-oriented programming model. They allow you to control the visibility of your class members and classes, which can help you to write more secure and maintainable code.