Intermediate · Inheritance, polymorphism and interfaces · topic 25 of 60 · 20 min
Packages and access modifiers
Explanation
Why packages?
A real application has hundreds of classes. Packages organise them by area (billing, orders, users) and prevent name clashes: your com.shop.billing.Invoice and a library's org.pdf.Invoice can both exist. The package name usually starts with a reversed domain name the team owns (com.mycompany.app) and matches the folder structure.
// file: src/main/java/com/shop/billing/Invoice.java
package com.shop.billing; // must be the first statement
import java.time.LocalDate; // one class
import java.util.*; // every class in java.util (not sub-packages)
import com.shop.orders.Order; // a class from another package of your app
public class Invoice {
private final Order order;
private final LocalDate date = LocalDate.now();
public Invoice(Order order) { this.order = order; }
}The fully qualified name of a class is its package plus its name: com.shop.billing.Invoice. You can always use that full name instead of importing (java.util.List<String> list). Classes in java.lang (String, Math, System, Integer) are imported automatically.
The four access levels
| Modifier | Same class | Same package | Subclass (other package) | Everywhere |
|---|---|---|---|---|
| private | Yes | No | No | No |
| (none) package-private | Yes | Yes | No | No |
| protected | Yes | Yes | Yes | No |
| public | Yes | Yes | Yes | Yes |
- Fields: almost always private.
- Methods: public if other packages need them; package-private for helpers used inside the package; private for internal steps.
- Classes: a top-level class is either public or package-private. Only one public top-level class per file.
- protected: for members that subclasses need; use sparingly, because subclasses in other packages then depend on them.
Static imports
import static java.lang.Math.max;
import static java.lang.Math.PI;
double r = max(2.5, 3.0) * PI; // no Math. prefixModules in one sentence
Since Java 9, the Java Platform Module System (module-info.java) can group packages into modules with explicit exports; most application code and frameworks still work at the package level, so you can learn modules later.
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Packages and access modifiers · 1/6
In this lesson you will organise classes into packages and control who can see what.
Prefer a video by a teacher? Find free videos on “java packages import access modifiers public private protected default” on YouTube ↗
In real life: A clinic app's package layout
A clinic management app is organised by feature. Classes used across features are public; helpers inside a feature are package-private, so other teams cannot depend on them by accident.
com.clinic.appointments → AppointmentService (public), SlotFinder (package-private)
com.clinic.patients → Patient (public), PatientValidator (package-private)
com.clinic.billing → Invoice (public), GstCalculator (package-private)
com.clinic.common → Money, PhoneNumber (public value types)Practice (0/3 done)
class Calc in package a has a method int add(int x, int y) with no modifier. A class in package b creates a Calc and calls add. What happens? (Assume Calc itself is public.)
Which class never needs to be imported?
Create a small project with two packages: com.shop.billing (public class Invoice, package-private class TaxCalculator) and com.shop.app (class Main). In Main, create an Invoice and print its total. Then try to use TaxCalculator from Main and write down the exact compiler error.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Abstract classesInheritance, polymorphism and interfaces · same module
- Overriding and polymorphismInheritance, polymorphism and interfaces · same module
- Packages, visibility and project layoutGo Programming (backend and cloud) · Packages, testing and generics
- Access modifiers, static members and encapsulationC# and .NET · Classes and objects
- Modules: import and exportJavaScript Programming (language in depth) · Modules, errors, JSON and dates
- Modules and importsPython Programming · Errors, modules and the standard library
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
Which modifier allows access from subclasses in other packages but not from unrelated classes there?
Answer: protected
protected adds subclasses to package access.
Where must the package statement be?
Answer: The first statement of the file
package comes before imports and types.
What is the fully qualified name of class Order in package com.shop.orders?
Answer: com.shop.orders.Order
Package name plus class name.
Which is the usual access level for fields?
Answer: private
Encapsulation keeps fields private.
What is the usual package name for files in folder internal/store?Related
Answer: store
By convention the package name matches the last part of the folder path.
Who can access an internal class?Related
Answer: Any code in the same assembly (project)
internal means visible inside the same assembly.
What does import * as tax from "./tax.js" give?Related
Answer: An object with all named exports
A namespace import collects all exports into one object.
Which import lets you write sqrt(25) without math. in front?Related
Answer: from math import sqrt
from math import sqrt brings the name sqrt straight into your program.
From Modules and imports
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- This is the last topic of “Inheritance, polymorphism and interfaces”. The module exam comes next.
- Module 5 exam: Inheritance, polymorphism and interfaces · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Exceptions and generics. 60 topics left in the course before the final exam.