Sub topic 2
Packages and Where Access Occurs
A Java program can contain many classes. A package is a named group of related Java types, such as classes. Packages help you organize those classes and tell Java which class you mean when names are similar.
Packages also matter for access. Access is permission for one part of a program to use a class or one of its members. A member is a field, method, or other item declared inside a class. When Java checks some kinds of access, it looks at the package where the access is written.
In this chapter, you will create two packages, run a small program, and see why code in one package can use a method that code in another package cannot.
What a package name does
A package name gives a class a place in the program’s naming system. For example, a class named PriceCard could belong to the package com.example.store.
Its fully qualified name is its package name followed by its class name:
com.example.store.PriceCard
The fully qualified name identifies the class more precisely than PriceCard alone. Two classes can have the same simple name if they are in different packages. For example, com.example.store.Report and com.example.school.Report are different classes.
Package names often use lower-case words separated by dots. A common convention is to start with a reversed internet domain name, such as com.example. This helps different organizations choose distinct names. You do not need to own a domain to follow the examples in this chapter.
Declaring a package
A package declaration is a statement that says which package a Java source file belongs to. Put it at the start of the file, before imports and class declarations:
package com.example.store;
public class PriceCard {
}The semicolon ends the statement. The package name is case-sensitive: com.example.store and com.example.Store are different names.
Classes declared in files with the same package declaration belong to the same package, even when they are in separate files. The declaration determines the package; an import does not.
Package names and folders
For ordinary Java projects, the folder path follows the package name. The dots become folder separators. A source file for com.example.store.PriceCard would commonly be stored at:
src/com/example/store/PriceCard.java
Here, src is the source root: the folder above the package folders. The source root can have a different name. What matters in this example is that com/example/store matches the package name.
The file name PriceCard.java also matches the public class name PriceCard. Java requires this match for a public top-level class, which is a class declared outside another class.
Using a class from another package
An import is a statement that lets you use a class’s simple name in a source file. For example:
import com.example.store.PriceCard;
After that import, the file can refer to the class as PriceCard instead of writing com.example.store.PriceCard each time.
An import does not move the class into the importing file’s package. It also does not grant access that the file would not otherwise have. It only helps Java find the intended name.
You can also write the fully qualified name without an import. This is useful when two classes have the same simple name. A file cannot use single-class imports for two different classes with the same simple name. Instead, use a fully qualified name for at least one of them.
Classes in the same package can normally refer to one another by simple name without an import. Java also makes classes in the java.lang package, such as String, available by simple name.
An import ending in .* makes names of accessible types in one package available. It does not import types from that package’s subpackages. For example, import java.util.*; does not import types from java.util.concurrent.
Package names with dots
It is easy to mistake a longer package name for part of a shorter one. Consider these names:
com.example.storecom.example.store.reports
They are different packages. The second name begins with the first, but that does not make the two packages the same for access checks.
The dots help people organize names. They do not give a package special access to another package whose name shares the same beginning. Code in com.example.store.reports is outside com.example.store.
Worked example: access from two packages
The following program uses three classes:
PriceCardandShelfLabelare incom.example.store.Reportis incom.example.store.reports.ShelfLabelreads a method that is available within its package.ReportcallsShelfLabel, but it cannot read that method directly.
A method with no access modifier, such as public or private, has package-private access. For this example, that means code in the same package can call it, but code in the other package cannot.
You need a Java Development Kit, or JDK, installed to try this example. A JDK provides javac, the Java compiler, and java, the command that runs the compiled program. A compiler turns Java source files into class files that Java can run.
The folder commands below use a Bash-style shell, such as a terminal on macOS or Linux. Start in an empty working folder and create the source folders:
mkdir -p src/com/example/store/reportsCreate the classes
Save this file as src/com/example/store/PriceCard.java:
package com.example.store;
public class PriceCard {
public PriceCard() {
}
public String category() {
return "Book";
}
int cents() {
return 1250;
}
}The category method is public, so the other package can call it in this example. The cents method has no access modifier. It returns a price in cents, so 1250 means 12 dollars and 50 cents.
Save this file as src/com/example/store/ShelfLabel.java:
package com.example.store;
public class ShelfLabel {
public static String format(PriceCard card) {
return card.category() + ": " + card.cents() + " cents";
}
}ShelfLabel and PriceCard declare the same package. Therefore, the call to card.cents() is written in the same package as PriceCard.
Save this file as src/com/example/store/reports/Report.java:
package com.example.store.reports;
import com.example.store.PriceCard;
import com.example.store.ShelfLabel;
public class Report {
public static void main(String[] args) {
PriceCard card = new PriceCard();
System.out.println("Category: " + card.category());
System.out.println(ShelfLabel.format(card));
// System.out.println(card.cents());
}
}The two imports let Report use the simple names PriceCard and ShelfLabel. They do not make Report part of com.example.store.
The line beginning with // is a comment, so Java does not run it. You will use it to test access after running the program.
Compile and run
From the working folder, compile all three files:
javac -d out src/com/example/store/PriceCard.java src/com/example/store/ShelfLabel.java src/com/example/store/reports/Report.javaThe -d out option tells the compiler to put the class files under the out folder. The compiler creates the package folders there as needed.
Run the program with:
java -cp out com.example.store.reports.ReportThe -cp out option puts out on the classpath. The classpath tells Java where to look for classes. Use the folder above com, not the reports folder itself. Give java the fully qualified class name, without .java or .class.
The output is:
Category: Book
Book: 1250 centsFind the place where access occurs
Look closely at the call to cents. It is written inside ShelfLabel, which belongs to com.example.store. That is the same package as PriceCard, so the package-private call is allowed.
Report starts the program and calls ShelfLabel.format(card). But that does not move the code inside ShelfLabel into the reports package. The access to cents still occurs in the code written in ShelfLabel.
Now test the difference. In Report.java, remove the // from this line:
System.out.println(card.cents());
Run the same javac command again. Compilation should fail. The compiler message says that cents is not public and cannot be accessed from outside its package.
The call is now written in Report, which belongs to com.example.store.reports. That package is different from com.example.store, even though their names share a prefix. The import of PriceCard does not change that.
Put the // back and compile again before continuing. A failed compilation may leave older class files in out, so do not assume that running java after a failed compile tests your latest source changes.
The key question is not “Who started the program?” It is “Where is the code that uses this member written?”
| Access written in | Target | Result in this example |
|---|---|---|
| `ShelfLabel`, in `com.example.store` | `PriceCard.cents()` | Allowed: same package |
| `Report`, in `com.example.store.reports` | `PriceCard.cents()` | Not allowed: different package |
| `Report`, in `com.example.store.reports` | `PriceCard.category()` | Allowed: the method is public |
Common package mistakes
Assuming an import changes access
If a class has an import for PriceCard, Java can recognize the simple name. The import does not turn a package-private method into a public one. If an access fails, check both the package declaration of the file using the member and the member’s access.
Treating a subpackage as the same package
A class in com.example.store.reports does not share package-private access with a class in com.example.store. Compare the complete package names, not just their first few words.
Running with the wrong class name or classpath
For the example, Report is not enough as the name passed to java. Use com.example.store.reports.Report. The classpath must also point to out, the folder above the package folders.
Forgetting the package declaration
A source file with no package declaration belongs to an unnamed package. This can be convenient for a tiny practice program, but it makes a poor foundation for a multi-package project. In particular, code in a named package cannot import a class from the unnamed package. Use named packages for the files in this example.
Practice
Exercise
A file declares package com.example.store; and imports com.example.store.reports.Report. Which package does the file belong to?
Show answer
It belongs to com.example.store. The import lets it refer to Report by simple name; it does not change the file’s package.
Exercise
In the worked example, why can ShelfLabel call PriceCard.cents() while Report cannot call it directly?
Show answer
ShelfLabel is in the same package as PriceCard. Report is in a different package, and cents has package-private access.
Exercise
A class is declared as com.example.store.reports.Report, and its class file is under out/com/example/store/reports. What command runs it from the working folder?
Show answer
Run java -cp out com.example.store.reports.Report.