Access Modifiers
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
Description
public
access modifier allows unrestricted access to a class, method, or variable from any other class.
Example
Private
Description
private
access modifier restricts access to members within the same class. They are not accessible from outside the class.
Example
Protected
Description
protected
access modifier allows access to members within the same package or subclasses, even if they are in different packages.
Example
Default (Package-private)
Description
Members with no access modifier (also known as package-private) are accessible only within the same package.
Example
Brief Comparison Table
Access Modifier | Visibility | Accessible from Same Class | Accessible from Subclasses | Accessible from Same Package | Accessible from Different 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 |
Summary
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.
Last updated