[!NOTE] As your application grows from 5 files to 5,000 files, throwing everything into a single folder becomes chaos. Java uses a strict "Package" system mapped directly to your operating system's folders.
Packages (Folders)
A package is simply a directory structure. To avoid naming colllisions globally (where two companies both create a DatabaseConnection class), Java conventionally uses reversed internet domain names as the root package structure.
If your company domain is google.com, your project structure might look like this:
src/
└── com/
└── google/
└── auth/
└── LoginManager.java
└── database/
└── QueryExecutor.java
At the absolute very top line of LoginManager.java, you MUST declare the package it lives inside:
// Line 1: Package declaration
package com.google.auth;
// Now we import classes from OTHER packages
import java.util.Scanner;
import com.google.database.QueryExecutor;
public class LoginManager { ... }
Access Modifiers Matrix
We briefly touched on public and private. But there are actually 4 distinct levels of visibility in Java. Understanding this matrix is critical for interview questions.
| Modifier | Access inside same Class | Access inside same Package | Access from a Subclass (Child) | Access from the World everywhere |
|---|---|---|---|---|
public |
✅ | ✅ | ✅ | ✅ |
protected |
✅ | ✅ | ✅ | ❌ |
| (default) | ✅ | ✅ | ❌ | ❌ |
private |
✅ | ❌ | ❌ | ❌ |
The "Default" (Package-Private) Mystery
If you write a variable without ANY keyword (e.g., String token;), it defaults to Package-Private.
Any other class living in the exact same folder (package) can see and modify that variable. But if a class in a different folder tries to access it, the compiler throws an error.
When to use what?
- Use
privatefor 99% of your instance variables to enforce Encapsulation. - Use
publicfor classes, constructors, and methods you want the whole application to use (like a.saveData()method). - Use
protectedfor variables that you want to hide from developers, but allow inheriting Child classes to manipulate directly for performance logic.