Sub topic 2
Declaring a package
This chapter assumes you can write a class with fields, methods and a main method, and that you can compile and run it from a terminal or an IDE. It covers the package declaration: what it does, where it goes, and the errors it causes when misused. Naming rules, directory layout, imports and access control each get their own chapter, so they appear here only as far as the declaration needs them.
What a package declaration does
A package declaration is a single statement at the top of a source file. It says which package the types in that file belong to.
package com.example.shop.model;
public class Product {
private final String name;
private final double price;
public Product(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
}The declaration has two effects:
- It sets the fully qualified name of every top-level type in the file. The class above is
com.example.shop.model.Product, not justProduct. Two classes with the same simple name can exist as long as their packages differ. - It decides which classes count as "in the same package". That determines who can use members with no access modifier. The access chapter covers this in detail.
A package is a namespace. It is not a container object you can create or inspect in your code, and it has no members of its own beyond the types declared in it.
The rules of the declaration
The syntax is the keyword package, a dotted name and a semicolon. The rules below cause most beginner errors.
- Position. The declaration must come before every
importand before every type declaration. Only whitespace and comments may precede it. - Count. A file has at most one package declaration. It applies to every top-level type in that file.
- Scope. The declaration affects only its own file. Other files must declare the package themselves.
- Absence. A file with no declaration belongs to the unnamed package (also called the default package). A later chapter explains why to avoid it.
A file may contain several top-level types, but at most one can be public, and it must match the file name. All of them share the one package:
package com.example.shop.model;
public class Order {
private final Product product;
private final int quantity;
public Order(Product product, int quantity) {
this.product = product;
this.quantity = quantity;
}
public double total() {
return product.getPrice() * quantity;
}
}
class OrderLine {
// Package-private: visible only inside com.example.shop.model
}Order can use Product by its simple name here because both are in com.example.shop.model. No import is needed for classes in your own package.
Packages are flat, not nested
Names like com.example.shop and com.example.shop.model look like a parent and a child. The language does not treat them that way. They are two unrelated packages that share a naming prefix.
This has three consequences:
- Declaring
package com.example.shop;does not give you access to the classes incom.example.shop.model. - A class in
com.example.shop.modelcannot usecom.example.shoppackage-private members. - Importing
com.example.shop.*does not import anything fromcom.example.shop.model.
The hierarchy exists in your head and on disk, where directories nest. The compiler does not use it for access or name lookup.
Using a packaged class from another package
Main lives in a different package, so it must either import Product or write its full name. Importing is covered in later chapters. This is the shortest working form:
package com.example.shop;
import com.example.shop.model.Product;
public class Main {
public static void main(String[] args) {
Product p = new Product("Pen", 1.5);
System.out.println(p.getName() + " costs " + p.getPrice());
}
}Notice the order in the file: package first, then import, then the class.
Declaration and directory must agree
The compiler does not require the source file's directory to match the package, when you give javac the file paths yourself. The runtime is different. The java launcher finds classes by turning the package name into a directory path under the classpath. For com.example.shop.Main it looks for com/example/shop/Main.class.
The convention that keeps everything working is to mirror the package in the source tree:
| Package declaration | Source file location |
|---|---|
| `com.example.shop` | `src/com/example/shop/Main.java` |
| `com.example.shop.model` | `src/com/example/shop/model/Product.java` |
Compile with -d so the class files land in matching directories, then run by fully qualified name:
javac -d out src/com/example/shop/Main.java src/com/example/shop/model/Product.java
java -cp out com.example.shop.MainThe output is Pen costs 1.5. After compiling, out/ contains com/example/shop/Main.class and com/example/shop/model/Product.class. The -d option creates those directories for you.
Common errors
Most problems with package declarations fall into a few patterns. The messages below are typical javac and java output, and exact wording varies by version.
| Symptom | Likely cause | Fix |
|---|---|---|
| `class, interface, enum, or record expected` near the package line | `package` appears after an `import` or a type, or a second `package` line exists | Move it to the top, and keep only one |
| `package com.example.shop.model does not exist` on an import | The package was never compiled, or `-cp` or `-d` points to the wrong place | Compile the model file too, and check the classpath |
| `Could not find or load main class Main` | The class is in a package, but you ran it by its simple name | Run `java -cp out com.example.shop.Main` |
| `Could not find or load main class com.example.shop.Main` and `Wrong name` | The class file is in a directory that does not match its package | Rebuild with `javac -d` so directories mirror packages |
| `Product is not public in com.example.shop.model; cannot be accessed from outside package` | The type has no `public` modifier | Make the class `public`, or use it only from its own package |
| `cannot find symbol` for a class you know exists | The class is in another package and has no import | Add an import, or use the fully qualified name |
Two further mistakes are quieter. Running java com.example.shop.Main from inside the out/com/example/shop directory fails, because the launcher resolves the package path from the classpath root, not the current directory. Also, moving a file into a package without editing its declaration compiles fine in some setups and then breaks at run time, so change both together.
Package-private by default
Leaving off an access modifier makes a top-level type or a member package-private. Only code in the same package can see it:
package com.example.shop.model;
class PriceFormatter {
static String format(double price) {
return String.format("%.2f", price);
}
}Product and Order can call PriceFormatter.format(...). A class in com.example.shop cannot, and it cannot even import PriceFormatter, because the type itself is hidden. This is the first practical reason the package declaration matters. It lets you keep helpers out of your public surface without any extra keyword.
Packages with no types: package-info.java
A package can have a special file named package-info.java. It contains only a package declaration, optionally preceded by documentation and annotations:
/**
* Domain classes for the shop: products, orders and related types.
*/
package com.example.shop.model;This is the one place where the Javadoc comment and annotations for a package itself can live. You do not need it to make a package exist, since a package exists once a file declares it, but it is the standard spot for package-level documentation.
Checking your understanding
Exercise
A file begins with import java.util.List; and the next line is package com.example.util;. What happens when you compile it, and what is the fix?
Show answer
The compiler reports an error such as "class, interface, enum, or record expected", because the package declaration must come before all imports and type declarations. Fix it by moving package com.example.util; to the top of the file, above the import. Comments may stay above it.
Exercise
You compile src/com/example/shop/Main.java with javac -d out ..., and then run java -cp out Main. Why does this fail, and what command works?
Show answer
Main is declared in com.example.shop, so its real name is com.example.shop.Main. The launcher looks for out/Main.class, which does not exist. Run java -cp out com.example.shop.Main.
Exercise
com.example.shop declares a package-private class Cart. A class in com.example.shop.model tries to use it. Does the shared name prefix make this legal?
Show answer
No. The two packages are unrelated for access purposes, and the prefix does not make one a parent of the other. The model class cannot see a package-private Cart. To share it, make Cart public and import it, or move the classes into the same package.