Access Modifiers
Last updated
Last updated
Access modifiers (Specifiers) in Java are keywords that control the visibility and accessibility of classes, methods, and variables. They ensure encapsulation, data hiding, and maintainability of code by regulating access to members.
public
access modifier allows unrestricted access to a class, method, or variable from any other class.
private
access modifier restricts access to members within the same class. They are not accessible from outside the class.
protected
access modifier allows access to members within the same package or subclasses, even if they are in different packages.
Members with no access modifier (also known as package-private) are accessible only within the same package.
public
Global
Yes
Yes
Yes
Yes
private
Local
Yes
No
No
No
protected
Package and Subclass
Yes
Yes
Yes
No
default
Package
Yes
No
Yes
No
Public: Use when you want unrestricted access to members.
Private: Use for encapsulation and to restrict access to members.
Protected: Use when you want members accessible within subclasses or the same package.
Default (Package-private): Use for package-level encapsulation and restricted access.
Choose the appropriate access modifier based on the desired level of encapsulation and access control required for your classes, methods, and variables.