Lesson · Packages & Access Control
Packages: folders that keep class names apart
16 min readPackages & Access Control
A package is a folder for classes plus the name prefix that keeps class names unique. The same folder boundary is what the default access level protects, which is why packages and access control are one topic.
Two classes walk into one folder
You add a second class called Report to a project that already has one, in the same folder:
class Report { ... } // team A wrote this yesterday class Report { ... } // your new one, same folder // javac: error: duplicate class: Report
Predict: the two classes belong to unrelated features (a school report and a work report). How can both exist in one program at the same time? Your laptop already solved this puzzle: two files named cat.jpg can live in different folders. Java's folders for classes are called packages.
A package is a folder with a name
A package is a folder for classes plus the prefix that keeps names unique. Three pieces make it work:
| Piece | Example | What it does |
|---|---|---|
| Package declaration | package school.grades; on line one | Says which folder the file stands for: school/grades/ |
| Fully qualified name | school.grades.Report | The class's full name: package first, then the simple name |
| Import | import school.grades.Report; | A nickname, so the file can say Report instead of the full name |
- Folders are not optional. The compiler maps
package school.grades;to aschool/grades/directory; the dots in the name are just the folder path. - Wildcards save typing, nothing else.
import java.util.*;is shorthand for every class in that package; it adds nothing at runtime. - Same name, different package, no clash: two
Reportclasses coexist, and a file picks between them with its import or by writing the full name.
An import is a nickname, not a copy. The class stays in its package; the file simply stops spelling the whole path out.
The four doors, and who they open for
Packages are also the boundary that access control measures from. Access control is the question: which callers may read this field or call this method? One modifier per member decides:
| Modifier | Who may use the member |
|---|---|
private | Only code inside the same class |
| no modifier (package-private) | Any code in the same package |
protected | The same package, plus subclasses in other packages |
public | Any code anywhere |
- Start narrow: every field is
privateuntil a caller genuinely needs it. - Helpers shared by classes in one folder stay package-private: no keyword, and no promise to the outside world.
protectedis the door built for subclasses; it reaches into other packages too, with one quirk worth knowing.publicis a promise to every caller you will ever have; make it the smallest and most deliberate choice.
Think of each level as a door into a room. private is your desk drawer, package-private is the office, protected adds a door for an heir, public is the street.
Try the doors yourself
Pick a modifier, then pick where the caller stands. The playground judges each combination with the compiler's own rules:
privateis the strictest: not even a subclass may look in.- Package-private (no modifier) is the default, and the one everyone forgets: another package loses access and the compiler says so loudly.
protectedworks from a subclass in another package, with a quirk: the subclass may touch the member through itself, not through a plain parent reference.publiccrosses every boundary; use it for what callers must have, never for what is merely convenient.
The quirk is real and the compiler enforces it. A subclass in another package can read this.balance (inherited state), but other.balance on a parent-typed reference is refused. The rule exists so the parent's package keeps control over its own state.
Access playground · who may touch the member
private int salary;The member's modifier
The caller stands in
package school
package office
Denied
Even a class in the same folder cannot see a private member: private is about the class, not the package.
Verified against the compiler: the protected quirk (through itself, not through a parent reference) is a real error, not a simplification. Package-private denials were checked the same way.
Package design for beginners
Two habits cover most package decisions:
- Name by story, not by layer.
school.grades,shop.ordersandpaymentsage well;models,utilsandmiscturn into drawers of leftovers. - Keep the public surface small. A class with no modifier is visible only inside its package; lean on package-private helpers and make classes
publiconly where outsiders need them. - One folder per package, one package per feature. Moving a class between packages should mean its story changed, not that the file count changed.
Packages organise names; modules enforce boundaries. A package is a folder with a naming rule, not a vault: treat it as design structure rather than protection from hostile code.
The package playbook
Bringing a class into the world, in order:
- Write the package declaration first (
package shop.orders;) and put the file inshop/orders/. - Decide the class's visibility: no modifier for internal helpers,
publiconly for what callers need. - Start every field
private; open it up only when a caller truly needs it. - For methods:
privateor package-private by default,protectedwhen subclasses are the audience,publicfor the actual API. - Import what you use, with specific imports where possible; the one line each costs keeps files readable.
The package decides who can see; the modifier decides who can touch. Two questions, two answers, and most access bugs come from answering them by accident.
A package is a folder with a name, and the first level of access control
The folder keeps same-named classes apart and the name prefix keeps them findable. From that same boundary, the four access levels measure their reach: private is one class, package-private is one folder, protected adds subclasses, public is everyone. Design the surface small: internal helpers stay hidden, and callers see only what they can rely on.
Interview angles
What is a package, in one sentence?+
A folder for classes plus the namespace that makes class names unique: school.grades lives in school/grades/, and its classes answer to school.grades.Report from outside.
The dots in the name are literally the folder path; the compiler and the java tool resolve that path through the classpath, the list of places they search for classes. Two classes named Report coexist as long as their packages differ.
package school.grades; import school.grades.Report; // same package: this line is redundant
Common misconception: That a package is just a label on a folder. It is also a namespace and an access boundary: the same file without its package declaration would clash with every other Report.
Follow-up: What decides which Report your source file actually uses?
What does the default access level do?+
A member with no modifier is package-private: every class in the same folder can use it, and nothing outside can.
It is the quiet workhorse for helpers: classes, methods and fields that belong to one feature's folder. If a helper moves to another package, callers fail at compile time, which is exactly the signal you want.
class Helper { } // package-private class: one folder only List<String> names; // package-private field: one folder only
Common misconception: That no modifier means public. It is the middle door: same folder only, and it is the level people forget to write on purpose.
Follow-up: When would you choose package-private over private?
How does `protected` behave across packages?+
A subclass in another package gets access through itself: this.balance works, while other.balance on a parent-typed reference is refused by the compiler.
The qualifier rule keeps the parent's package in control: from outside, protected access is allowed only through a reference whose type is the subclass (or below it). Inside the same package, protected behaves like the default level.
// package office; class Staff extends school.Teacher int readSelf() { return balance; } // fine int readOther(Teacher t) { return t.balance; } // error: protected access
Common misconception: That protected means 'public for subclasses'. It is public for subclasses only through themselves; everything else stays as closed as the package wants.
Follow-up: Why would the language add that qualifier rule?
When do you need `import`?+
Only when the file wants the short name. Without any import, write java.util.Scanner in full; with import java.util.Scanner;, Scanner works.
Imports are compile-time nicknames and produce no code. A wildcard imports every visible name of a package; if two imports offer the same simple name, the compiler refuses the short name and demands the full one, which keeps ambiguity visible instead of guessing.
import java.util.List; // nickname import java.util.*; // every name in java.util
Common misconception: That wildcard imports slow a program down or copy classes in. They change nothing at runtime; the compiled code is identical.
Follow-up: What happens when two imports both define the same simple name?
Are packages a security boundary?+
No. They are a design boundary checked by the compiler, not a vault; tools like reflection can reach through in ways your design should never depend on.
The module system (Java 9 and later) strengthens boundaries by declaring which packages are exported, but packages themselves stay organisational units. Treat access levels as intent and structure, not as protection against hostile code.
Common misconception: That private fields make data inaccessible. They make it inaccessible to ordinary source code; debugging tools, serialisation and reflection have their own doors.
Follow-up: What does the module system add on top of packages?