Access Modifiers & Packages
public: accessible from anywhere. private: only within that same class. protected: within the same package + subclasses. default (no modifier written): only within the same package.
A package is a folder/group of related classes — like java.util, which holds collection classes such as List and Map. To create your own package you write "package com.code10x;".
package com.code10x;
public class Robot {
private int battery;
protected void charge() { battery = 100; }
}- public/private/protected/default = 4 levels
- Package = a group of related classes
- Access control is essential for encapsulation
Java has 4 access levels, and their effect depends on where the accessing code is — the same class, the same package, a subclass (even in a different package), or the whole world (anywhere).
| Modifier | Same Class | Same Package | Subclass (diff package) | World |
|---|---|---|---|---|
| public | ✅ | ✅ | ✅ | ✅ |
| protected | ✅ | ✅ | ✅ | ❌ |
| default (no modifier) | ✅ | ✅ | ❌ | ❌ |
| private | ✅ | ❌ | ❌ | ❌ |
Every .java file can start with "package com.code10x.model;" — the folder structure must match the package name (the file should live in a com/code10x/model/ folder). To use it elsewhere, you write "import com.code10x.model.Student;", or for the whole package, import com.code10x.model.*;
The java.lang package (String, Integer, System, etc.) is automatically imported in every file, no explicit import needed.
import static lets you use static members directly, without the class-prefix — like after import static java.lang.Math.*;, you can write sqrt(25) directly, instead of Math.sqrt(25). Overusing this can make code confusing (unclear where a method came from) — so use it sparingly, it's mainly common in test frameworks (JUnit's assertEquals).
The classpath tells the JVM where to find compiled .class files and libraries. Modern build tools (Maven, Gradle) manage the classpath automatically (downloading dependencies and placing them in the right spot), but it's important to understand how the JVM finds classes at runtime — if you see a "ClassNotFoundException", it's often a classpath issue.