library
beginnerAccess Modifiers
Understand the four access levels in Java and their scope: private, default, protected, public.
Java has four access modifiers that control visibility at compile time:
Private = your diary (only you read it). Default = office memo (everyone in the department sees it). Protected = family secrets (relatives know, even in other cities). Public = newspaper (everyone reads it).
Key Concepts
1
private — visible only within the declaring class. Not inherited by subclasses (they can't see it, though it exists in memory). Use for internal implementation details.
2
default (package-private, no keyword) — visible to all classes in the same package. The most overlooked modifier. Use for package-internal APIs that shouldn't leak outside.
3
protected — visible to the same package AND to subclasses in any package. Subclass access works only through inheritance (via this, not via an external reference). Use for methods subclasses need to override or call.
4
public — visible everywhere. Use for the public API.
5
Access rules for overriding: an overriding method cannot be more restrictive than the parent. You can widen (protected → public) but not narrow (public → private).
6
Top-level classes can only be public or default (package-private). Inner classes can use all four modifiers.
7
Common interview question: can a private method be overridden? No — it's invisible to the subclass. If the subclass declares a method with the same signature, it's a new method, not an override.