Access Modifiers
About
Access modifiers in Java are keywords used to specify the accessibility or visibility of classes, methods, variables, and constructors. They control how these elements can be accessed from other classes or packages. Java provides four types of access modifiers.
public
Visible to all classes
Visible to all classes
Allows unrestricted access to the method or field from any other class. Useful for methods that need to be accessible across packages.
protected
Only visible to subclasses and classes in the same package
Visible to subclasses and classes in the same package
Provides visibility within the same package and to any subclass, regardless of the package. Helpful for methods that should only be accessible to subclasses.
default
Package-private: visible only to classes in the same package
Package-private: visible only to classes in the same package
Restricts visibility to the same package. Useful for methods or fields intended for internal use within a package structure.
private
Not applicable to top-level classes
Visible only within the same class
Only accessible within the class itself.
Public
Accessible from anywhere, both within the same package and from other packages.
Usage: Use
public
when you want a member to be widely accessible by any code.Example:
Protected
Accessible within the same package and by subclasses (even if they are in different packages).
Usage: Use
protected
when you want to provide access to the member within the same package and to subclasses.Example:
Default (Package-private)
Accessible only within the same package. When no access modifier is specified, it defaults to package-private.
Usage: Use the default access level when you want to restrict access to the member within the same package.
Example:
Private
Accessible only within the same class.
Usage: Use
private
when you want to encapsulate the member and prevent access from outside the class.Example:
Last updated
Was this helpful?