Java Access
Modifiers
Master the four levels of visibility control in Java: understand how public, private, protected, and package-private protect your code.
What Are Access Modifiers?
Access modifiers are keywords in Java that control which parts of your code can see and use a class, method, or variable. They are the foundation of encapsulation: the principle of hiding internal details and exposing only what is necessary.
Why Do They Matter?
The Four Levels of Access
Visibility Scope Diagram
The Core Rule
protected vs. package-private
These two are the most commonly confused. The critical difference is what happens outside the package.
| protected | package-private | |
|---|---|---|
| Same class | ✓ | ✓ |
| Same package | ✓ | ✓ |
| Subclass (different pkg) | ✓ | ✕ |
| Non-subclass (different pkg) | ✕ | ✕ |
How to Choose the Right Modifier
Example: private Fields
Example: protected in Inheritance
Example: Package-Private Default
Modifiers on Classes
Top-level classes (not nested) can only be public or package-private. You cannot declare a top-level class as private or protected.
Worked Example: Designing a Class
Common Mistakes
Complete Comparison Table
| Scope | public | protected | default | private |
|---|---|---|---|---|
| Same class | ✓ | ✓ | ✓ | ✓ |
| Same package | ✓ | ✓ | ✓ | ✕ |
| Subclass (other pkg) | ✓ | ✓ | ✕ | ✕ |
| Non-subclass (other pkg) | ✓ | ✕ | ✕ | ✕ |
Question 1 of 5
A field declared with no access modifier in Java has what level of visibility?
Question 2 of 5
Which access modifier should you use for a field that stores sensitive data (like a password) in a class?
Question 3 of 5
A protected method in class Animal (package: creatures) can be accessed by which of the following?
Question 4 of 5
Which of the following is NOT a valid access modifier for a top-level class in Java?
Question 5 of 5
Class A is in package com.app.models. It has a field int count with no access modifier.
Class B is in package com.app.models and is not a subclass of A.
Class C is in package com.app.views and extends A.
Class D is in package com.app.views and does not extend A.
Which classes can access A.count?