Java Access Modifiers and Package-Level Access
🔐 Java Access Modifiers and Package-Level Access
Java provides four access levels:
Access Modifier | Class | Package | Subclass | World (outside package) |
---|---|---|---|---|
public | ✅ | ✅ | ✅ | ✅ |
protected | ✅ | ✅ | ✅ | ❌ |
(default) no modifier | ✅ | ✅ | ❌ | ❌ |
private | ✅ | ❌ | ❌ | ❌ |
📦 How It Works in Packages
1. public
-
Accessible from any class in any package.
-
Typically used when a class or method needs to be globally available.
Example:
2. protected
-
Accessible within the same package and also by subclasses in other packages.
-
Often used in inheritance scenarios.
Example:
3. Default (no modifier)
-
Package-private: accessible only within the same package.
-
Used when you want a class or method to be hidden from other packages.
Example:
-
This class
A
cannot be accessed from a class in a different package.
4. private
-
Accessible only within the same class.
-
Not accessible from other classes even in the same package.
-
Commonly used for data hiding.
Example:
🧠 Key Points for Instructors
-
Default access is often misunderstood — remind students it's only package-level.
-
protected
offers the most nuanced behavior, useful when mixing packages and inheritance. -
Best practice: make class members
private
, then expose functionality usingpublic
orprotected
methods if needed.
✅ Summary Table
Modifier | Accessible in Same Class | Same Package | Subclass (other package) | Unrelated Class (other package) |
---|---|---|---|---|
public | ✅ | ✅ | ✅ | ✅ |
protected | ✅ | ✅ | ✅ | ❌ |
default | ✅ | ✅ | ❌ | ❌ |
private | ✅ | ❌ | ❌ | ❌ |
Comments
Post a Comment