Packages and Access Modifiers
Packages and Access Modifiers
Real Java code is organized in packages and uses access modifiers to control who can see classes, methods, and fields. Interviewers often ask about visibility and encapsulation.
Packages
A package is a namespace. It matches folder structure: package com.froquiz.utils; means the class lives in com/froquiz/utils/. Use the package at the top of the file:
javapackage com.froquiz.model; public class User { private String id; private String name; // ... }
To use a class from another package, use import: import com.froquiz.model.User; or import com.froquiz.model.*; (import all classes in that package). Classes in the same package do not need an import.
Access modifiers
| Modifier | Same class | Same package | Subclass | Everywhere |
|---|---|---|---|---|
| private | yes | no | no | no |
| (default) | yes | yes | no | no |
| protected | yes | yes | yes | no |
| public | yes | yes | yes | yes |
- private: Only inside the same class. Use for fields and internal helpers. Encapsulation means expose behavior via public methods, hide data.
- default (package-private): No keyword. Visible only in the same package.
- protected: Visible in the same package and in subclasses (even in another package).
- public: Visible everywhere. Use for the API you want to expose.
Encapsulation in practice
javapublic class Account { private double balance; // hidden public void deposit(double amount) { if (amount > 0) balance += amount; } public double getBalance() { return balance; } }
Callers cannot set balance directly; they use deposit and getBalance. That gives you control (e.g. validation, logging) and keeps the internal representation flexible.
You have completed the Java Fundamentals track. Finish this lesson to earn your certificate.