Nearby lessons

34 of 125

Java - 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:

ModifierSame classSame packageSub class (other package)Everywhere
privateYesNoNoNo
default (no keyword)YesYesNoNo
protectedYesYesYesNo
publicYesYesYesYes
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
JCode Cell
1class Example {
2 private int a = 10; // only inside this class
3 int b = 20; // default: same package only
4 protected int c = 30; // package + child classes
5 public int d = 40; // anywhere
6}
📝 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 Questions
Progress: 0 / 4