Nearby lessons
34 of 125Java - Access Modifiers
📌 What You Will Learn
- What a package is and why we need it
- How to create and use a package
- import statements — single and wildcard
- Access modifiers: public, protected, default, private
- The classpath and the jar tool
Access Modifiers is a core concept of the Java language. This lesson explains Access Modifiers — Who Can See What with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.
Access Modifiers — Who Can See What
Access modifiers control the visibility of classes, methods and variables. There are four levels:
| Modifier | Same class | Same package | Sub class (other package) | Everywhere |
|---|---|---|---|---|
| private | Yes | No | No | No |
| default (no keyword) | Yes | Yes | No | No |
| protected | Yes | Yes | Yes | No |
| public | Yes | Yes | Yes | Yes |
Trainer's Note: Memory trick: start from the most open to the most closed — public > protected > default > private. Only one modifier applies at a time. A top-level class can be only public or default.
In simple words: Visibility order: public > protected > default > private. Public is everywhere, protected also reaches child classes, default stays inside the package, and private stays inside the class.
Example01
📝 Key Takeaways
- Package = folder that groups related classes; first statement of the file.
- import mypack.*; brings in classes; java.lang is auto-imported.
- Access levels: public (everywhere) > protected (package + children) > default (package) > private (class only).
- Compile packages with javac -d . to create folder structure.
- Classpath tells JVM where classes live; jar packages many classes into one file.
- Reverse-domain package names (com.company.app) keep large projects safe from clashes.
🧠 Test Your Knowledge
4 QuestionsProgress: 0 / 4