Sub topic 1
Why Java Has Packages
Prerequisites
You should know how to write and run a Java class with a main method. You should also know basic classes, methods, fields, and command-line compilation.
Why Java Has Packages
A Java package is a named group of related classes. Packages provide two main benefits:
- They organize large programs into meaningful areas.
- They create namespaces, which prevent unrelated classes from having to use unique names.
For example, an application might separate com.example.shop.model.Product from com.example.shop.web.Product. Both classes have the simple name Product, but their fully qualified names are different.
Packages also control access. A class or member without an access modifier is package-private. Only code in the same package can use it directly.
Declaring a Package
Declare a package at the beginning of a source file, before the class declaration:
package com.example.shop.model;
public class Product {
private final String name;
public Product(String name) {
this.name = name;
}
public String getName() {
return name;
}
}The declaration makes the class's fully qualified name com.example.shop.model.Product. A package declaration applies to the entire source file, so one file cannot declare classes in different packages.
Naming Packages
Java convention uses lowercase package names. Projects commonly use a reversed domain name as the beginning:
com.example.shoporg.acme.reportingnet.company.weather
The reversed domain reduces collisions between organizations. Add meaningful project or feature names after it. Use dots to separate package levels, not underscores or hyphens.
Matching Packages to Directories
The source directory structure should mirror the package declaration. The previous class belongs in:
src/com/example/shop/model/Product.javaEach dot in com.example.shop.model becomes a directory separator. This arrangement lets Java tools locate source and compiled classes predictably.
The public class name must also match the filename. Therefore, public class Product belongs in Product.java, inside the directory that matches its package.
Exercise
What package and path should you use for a public class named Invoice in the package org.acme.billing?
Show answer
Use package org.acme.billing; and place the file at org/acme/billing/Invoice.java below the source root.