Sub topic 1
Why Java Has Packages
Prerequisites
This chapter assumes you can do the following:
- Write and run a basic Java class with a
mainmethod. - Read class, method, and field syntax.
- Compile Java code from a command line or an IDE.
You don't need to know the package or import syntax yet. The next chapters cover it. This chapter explains the problem packages solve, so the syntax makes sense when you meet it.
The problem: many classes, one shared space
A small program might have five classes. A real application has thousands, and it also pulls in libraries written by other people. Without any structure, three problems appear:
- Name collisions. Two teams both write a class called
Product,Logger, orDate. If every class lived in one global list of names, only one of them could exist. - No organization. A flat list of 3,000 classes gives a reader no hint about which ones belong together.
- No boundaries. Every class could use every other class's internals, so any change could break code anywhere.
A package is Java's answer to all three. It is a named group of related classes and interfaces. The group name becomes part of each class's identity.
A package is a namespace
A namespace is a scope in which each name is unique. Two classes can share a simple name if they sit in different namespaces. The package name plus the class name form the fully qualified name. For example, java.util.Date and java.sql.Date are two different classes. Date is the simple name and java.util or java.sql is the package.
The following three-file program shows the idea. The two Product classes coexist because they live in different packages.
package com.example.shop.model;
public class Product {
public String describe() {
return "shop product";
}
}This file belongs at src/com/example/shop/model/Product.java.
package com.example.warehouse;
public class Product {
public String describe() {
return "warehouse item";
}
}This file belongs at src/com/example/warehouse/Product.java.
package com.example.app;
public class Main {
public static void main(String[] args) {
com.example.shop.model.Product s = new com.example.shop.model.Product();
com.example.warehouse.Product w = new com.example.warehouse.Product();
System.out.println(s.describe());
System.out.println(w.describe());
System.out.println(s.getClass().getName());
}
}This file belongs at src/com/example/app/Main.java. Compile and run it from the directory that contains src:
javac -d out src/com/example/shop/model/Product.java src/com/example/warehouse/Product.java src/com/example/app/Main.java
java -cp out com.example.app.MainThe output is:
shop product
warehouse item
com.example.shop.model.ProductMain writes out the full names because it needs both classes at once. Chapters on imports show how to shorten this. The last line shows that the package is part of the class's runtime name. getName() returns the fully qualified name, not just Product.
Packages in the standard library
The Java standard library has thousands of classes. Packages keep it navigable. Each package name tells you the area of the class.
| Package | Contents |
|---|---|
| `java.lang` | Core types such as `String`, `Math`, and `Thread` |
| `java.util` | Collections and utilities such as `List` and `Scanner` |
| `java.io` | Input and output streams and files |
| `java.time` | Dates, times, and durations |
| `java.net` | Networking |
| `java.sql` | Database access through JDBC |
Application code uses the same mechanism. A typical project places its packages under one company or project prefix:
Each package has one clear job. A developer who needs the web layer knows which package to open.
Organizing code by cohesion
Packages work best when the classes in them change together and are understood together. Two common grouping strategies are:
- By layer:
model,service,repository,web. Each package holds one technical role. This is easy to learn, but one feature touches several packages. - By feature:
orders,customers,billing. Each package holds everything for one business area. A feature's code stays together, and a package can hide its internals from the rest of the program.
Neither is always right. Small applications often start by layer. Larger ones tend to move toward features, because feature packages make access control more useful (see the next section). Pick one convention per project and keep to it.
Packages as an access boundary
Packages also control visibility. Java has four access levels for classes and members: public, protected, package-private (no modifier), and private. The package-private level exists because packages exist. A class or method with no modifier is visible only to code in the same package.
This lets you build a package with a small public surface and hidden helpers. For example:
package com.example.shop.model;
class PriceFormatter {
static String format(double price) {
return String.format("%.2f", price);
}
}PriceFormatter has no public modifier, so only classes in com.example.shop.model can use it. If Main in com.example.app tries, the compiler reports an error like this:
error: PriceFormatter is not public in com.example.shop.model; cannot be accessed from outside packageThe practical effect is that other packages can't depend on PriceFormatter. You can rename it, change it, or delete it without breaking code outside the package. This is the main design benefit of packages beyond naming. A later chapter covers protected access and its package rule in detail.
What packages are not
Several misunderstandings cause real bugs. These are the main ones.
- Packages are not nested in a way that grants access.
java.utilandjava.util.concurrentlook like parent and child, but Java treats them as two unrelated packages. Being incom.example.shopgives a class no special access tocom.example.shop.model. Package-private access applies only within the exact same package. - A package is not a runtime container you can open. It is a naming and access concept compiled into each class file. There is no object that represents "the package" that you can instantiate.
- Packages do not replace good design. Placing classes in many packages without a clear reason adds import clutter and gives no benefit.
- Packages do not install dependencies. The package says where a class lives in the namespace. The classpath (covered in a later chapter) says where the compiler and JVM look for the files.
How the pieces fit together
This chapter introduced the purpose of packages. The mechanism has several parts, and each gets its own chapter.
| Part | Question it answers |
|---|---|
| `package` declaration | How does a class say which package it belongs to? |
| Naming conventions | How do you pick a name no one else will use? |
| Directory layout | Where must the files sit? |
| Fully qualified names | How do you refer to a class in another package? |
| Imports | How do you avoid writing the full name each time? |
| Classpath and `javac -d` | How do tools find the compiled classes? |
The unique-name question has a convention behind it. Organizations reverse their internet domain name, so example.com becomes com.example. Since domain names are already unique, the prefix keeps package names from clashing. That convention is why the examples here start with com.example.
Common errors at this stage
New Java developers hit a few predictable problems. Knowing them now helps when you start writing real package declarations.
- Assuming that a short name is unique. Searching your IDE for
DateorListfinds several classes. The package decides which one you mean. - Treating packages as folders only. The directory layout matters, but the
packageline inside the file is what the compiler records in the class. A file in the wrong folder with the rightpackageline can still confuse tools. - Making everything public. This removes the boundary benefit and makes later changes harder.
- Putting all classes in one package. It works for tiny programs but gives no organization or access control as the code grows.
Exercises
Exercise
A project has two classes that are both named Customer, one in com.example.billing and one in com.example.support. Why can both exist in the same program, and what is the fully qualified name of each?
Show answer
Each class belongs to a different package, so each package is a separate namespace and the simple name only needs to be unique inside its own package. The fully qualified names are com.example.billing.Customer and com.example.support.Customer.
Exercise
A class in com.example.shop.model has no access modifier. Can a class in com.example.shop.service use it? Can a class in com.example.shop.model use it? Does the nesting of the names change the answer?
Show answer
A class in com.example.shop.service cannot use it, because package-private access is limited to the exact same package. A class in com.example.shop.model can use it. The names look nested, but Java treats com.example.shop and com.example.shop.model as unrelated packages, so nesting does not change the answer.
Exercise
Name the three problems that a flat, single namespace of classes would cause, and say which package feature addresses each one.
Show answer
Name collisions are addressed by packages acting as namespaces, since the package name is part of the class's identity. Lack of organization is addressed by grouping related classes into named packages. Lack of boundaries is addressed by package-private access, which hides classes and members from other packages.