Lesson 13 of 23

In progress

Course progress

Java

Packages and visibility

Organise classes into packages, use imports without wildcards, and choose the access level that exposes the least.

A package is a namespace and an access boundary. It groups related classes, prevents name collisions and gives you a way to share code inside a module without publishing it.

What you will learn

  • Lay out packages and import classes.
  • Understand the four access levels.
  • Decide what belongs in a package.

Declaring and importing

package com.example.shop;
import java.util.List;
import java.time.LocalDate;
public class Order {
private final List<String> lines;
private final LocalDate placedOn;
Order(List<String> lines, LocalDate placedOn) {
this.lines = List.copyOf(lines);
this.placedOn = placedOn;
}
}

The package statement must be the first line, and the folder structure must match: com/example/shop/Order.java. The class’s full name is com.example.shop.Order, and that is what the runtime needs.

Imports are aliases for names. import java.util.List; lets you write List instead of java.util.List. An unused import is a warning in most tools and should be removed.

Wildcard imports (import java.util.*;) compile and are discouraged: they hide which classes a file depends on and can create an ambiguity when two packages share a name.

The four access levels

Modifier Visible to
private The class only
(none, package-private) Classes in the same package
protected Same package and subclasses
public Everywhere

The default is package-private, which is the least-known and most useful level. A class that only its package needs should not be public, because every public type is a commitment.

package com.example.shop;
class PriceCalculator {          // package-private
long total(java.util.List<Long> prices) {
return prices.stream().mapToLong(Long::longValue).sum();
}
}
public class Checkout {          // public facade
private final PriceCalculator calculator = new PriceCalculator();
public long total(java.util.List<Long> prices) {
return calculator.total(prices);
}
}

Checkout is the API. PriceCalculator can be renamed, split or deleted without affecting anyone outside the package.

Packages as design units

Group by feature or by layer, and be consistent:

com/example/shop/
Order.java
Checkout.java
pricing/PriceCalculator.java
pricing/Discount.java
storage/OrderRepository.java

Feature packaging keeps related changes together; layer packaging keeps technical concerns together. For a small application either works, and feature packaging tends to age better because a change touches one folder.

The signal of a bad package is a folder that everything imports from, with no clear theme. That is usually a "util" package that has become a dumping ground.

Naming

Package names are lowercase, dot-separated, and based on a domain you control: com.example.shop. Reversing the domain gives a globally unique namespace, which matters if the code is ever published.

Do not use hyphens or capitals; both cause problems with tooling. A single-word package such as shop is legal and collides easily.

Packages and the classpath

At compile time, -d out writes classes into a directory tree matching the packages. At run time, -cp out puts that tree on the classpath, and the JVM finds com.example.shop.Checkout at out/com/example/shop/Checkout.class.

That mapping is why folder layout and package declarations must agree. A mismatch produces NoClassDefFoundError at runtime, which is less helpful than the compile error you get when they disagree at build time.

Modules, briefly

The Java module system adds a module-info.java declaring which packages a module exports:

module com.example.shop {
requires java.sql;
exports com.example.shop;
}

That is stronger than packages: unexported packages are inaccessible even to public classes. Most applications do not need modules, and libraries increasingly ship them. Knowing the concept is enough until you build a library.

What to expose

A practical rule: start everything package-private, and make a class or method public when a caller outside the package needs it. That is the opposite of the IDE default, and it produces much smaller APIs.

Public types are hard to change later, because other code depends on them. Package-private types are free to evolve, which is where most of the design work happens.

Making a class public because a test in another package needs it. Move the test into the same package instead; tests are allowed to see package-private members, and the production API stays small.

Sketch a package layout for a small application with orders, customers and a database, naming three packages and saying which classes are public.

Show solution
com/example/shop/ Order.java public Customer.java public Checkout.java public pricing/PriceRules.java package-private pricing/Discount.java package-private storage/OrderRepository.java public interface storage/SqlOrderRepository.java package-private

The public surface is what a caller in another package needs: the domain types, the checkout entry point and the repository interface. Pricing rules and the SQL implementation stay package-private, so they can change without breaking anyone.

The repository interface is public because callers depend on the abstraction; the implementation is not, because nothing outside should construct it directly.

Recap

  • Packages are namespaces and access boundaries; declarations must match the folder layout.
  • Package-private is the default and the safest starting point for a new class.
  • Expose a small public facade and keep the rest inside the package.

Module 5 covers collections and errors: lists, maps, exceptions and files.

Can two packages have the same class name?
Yes, which is the point of packages. Use a fully qualified name when both are imported.
What is the unnamed package?
A class with no package declaration. It cannot be imported by classes in named packages, which is why it only suits throwaway examples.

Progress is saved in this browser only. No account, no email.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated November 16, 2026.