Skip to content

Intermediate · Inheritance, polymorphism and interfaces · topic 25 of 60 · 20 min

Packages and access modifiers

Explanation

Packages group related classes into folders with names like com.shop.billing, avoid name clashes and control visibility. You use classes from other packages with import (java.lang is imported automatically). Java has four access levels: public (everywhere), protected (package plus subclasses), default/package-private (same package only) and private (same class only).

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.

java
// 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

ModifierSame classSame packageSubclass (other package)Everywhere
privateYesNoNoNo
(none) package-privateYesYesNoNo
protectedYesYesYesNo
publicYesYesYesYes
  • 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.
Careful: Leaving out a modifier is NOT the same as public: a method with no modifier is package-private and invisible to other packages. The resulting error, "is not public in …; cannot be accessed from outside package", confuses many beginners when they move a class to a new package.

Static imports

java
import static java.lang.Math.max;
import static java.lang.Math.PI;
double r = max(2.5, 3.0) * PI;      // no Math. prefix
Use static imports sparingly, mainly for constants and test assertions.

Modules 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.

Think of it like this: Packages are like departments in a company (Accounts, HR, Sales) and access modifiers are like door permissions: private is your personal locker, package-private is your department room, protected adds trainees from other departments who report to you, and public is the reception area anyone can enter.
Tip: Organise packages by feature (com.shop.orders, com.shop.payments) rather than only by layer (controllers, services). Feature packages keep related classes together and let you hide more with package-private.

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

Packages and access

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.

output
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)
Feature packages with small public surfaces.

Practice (0/3 done)

Task 1 · Question

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.)

Task 2 · Question

Which class never needs to be imported?

Task 3 · Practice

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

Question 1

1.Which modifier allows access from subclasses in other packages but not from unrelated classes there?

Question 2

2.Where must the package statement be?

Question 3

3.What is the fully qualified name of class Order in package com.shop.orders?

Question 4

4.Which is the usual access level for fields?

Read more (free)

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.

From Packages, visibility and project layout

Who can access an internal class?Related

Answer: Any code in the same assembly (project)

internal means visible inside the same assembly.

From Access modifiers, static members and encapsulation

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.

From Modules: import and export

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

  1. This is the last topic of “Inheritance, polymorphism and interfaces”. The module exam comes next.
  2. Module 5 exam: Inheritance, polymorphism and interfaces · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Exceptions and generics. 60 topics left in the course before the final exam.

← Previous: Interfaces