Sub topic 6
Importing a single class
This chapter assumes you can write a Java class with fields and methods and that you know how to declare a package and match it to a directory. It also assumes you can compile and run a program from the command line or an IDE. Here you will learn exactly what a single-type import does, where it goes, how the compiler uses it, and which errors it produces.
What an import declaration does
A single-type import declaration names one class or interface by its fully qualified name. Inside that source file, you can then write the class's simple name.
import com.example.shop.model.Product;An import is a compile-time convenience for the names you type. It does not copy code, load the class, or link anything at runtime. The compiler resolves each simple name to a fully qualified name and writes the fully qualified name into the .class file. Two consequences follow:
- Removing an unused import changes nothing in the compiled output.
- Using
com.example.shop.model.Producteverywhere with no import produces the same bytecode as importing it.
An import also does not make the class available. The compiler must still find the class on the source path or classpath. The import only decides what a short name means.
Where imports go
A source file (a compilation unit) has this order:
- An optional
packagedeclaration. - Zero or more
importdeclarations. - Type declarations (classes, interfaces, enums, records).
Imports apply to the whole file. They are not scoped to a class or a method. Here are two files from a shop program. The first is src/com/example/shop/model/Product.java:
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 second is src/com/example/shop/Main.java:
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());
}
}Main is in com.example.shop, and Product is in com.example.shop.model. These are different packages, so the import is required. Compile and run from the directory that contains src:
javac -d out src/com/example/shop/Main.java src/com/example/shop/model/Product.java
java -cp out com.example.shop.MainThe program prints Pen costs 1.5.
How the compiler resolves a simple name
When the compiler sees a simple type name such as Product, it looks in a fixed order. The first match wins.
The practical rule is that a single-type import beats a class of the same name in your own package, and it beats anything brought in by a wildcard. That makes single-type imports the most explicit way to say which class you mean.
Importing nested classes
You can import a nested type by writing the enclosing class in the path:
import java.util.Map.Entry;After this, Entry<String, Integer> works without the Map. prefix. Importing java.util.Map alone does not import Entry. You would still write Map.Entry.
Subpackages are not included
Packages have no real hierarchy for import purposes. com.example.shop and com.example.shop.model are unrelated packages that happen to share a name prefix. Importing a class from one gives you nothing from the other. Likewise, Main in com.example.shop does not see Product just because model sits under it.
Redundant and duplicate imports
Some cases that look like mistakes are legal:
- Importing a class from your own package is allowed but pointless. The class is already visible.
- Importing
java.lang.Stringis allowed but pointless, becausejava.langis implicitly available. - Importing the same class twice is allowed. The compiler ignores the second one, and some IDEs flag it.
Importing two different classes with the same simple name is an error:
import java.util.Date;
import java.sql.Date; // error: a type with the same simple name Date is already definedDeclaring a class in the same file with the same simple name as an imported class is also an error. For example, a file that imports java.util.List and also declares its own class List will not compile. The fix for these cases is to import only one of the classes and write the other with its fully qualified name, as the DateConflict example below shows. A later chapter covers conflicts in detail.
import java.util.Date;
public class DateConflict {
public static void main(String[] args) {
Date utilDate = new Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
System.out.println(utilDate.getTime() == sqlDate.getTime());
}
}This prints true. Note that java.sql.Date is in the java.sql module, which the default JDK includes.
Common errors and what they mean
Forgetting the import. If Main uses Product without importing it, javac reports:
Main.java:6: error: cannot find symbol
Product p = new Product("Pen", 1.5);
^
symbol: class Product
location: class MainYou will see this error twice, once for the type and once for the constructor call. It means the simple name resolved to nothing.
A wrong package in the import line gives a different message:
Main.java:3: error: package com.example.store.model does not exist
import com.example.store.model.Product;
^This means the compiler could not find that package on the source path or classpath. Check for typos, and check that you passed the right -cp or -sourcepath.
A wrong class name inside a real package gives cannot find symbol on the import line itself. The error is on the import, not on a later use, so fix the import first.
Importing a class that exists but is not public gives:
Main.java:3: error: PriceFormatter is not public in com.example.shop.model; cannot be accessed from outside packagePackage-private classes can only be used from within their own package. An import cannot get around that.
A last case is the default package. A class with no package line cannot be imported by name from any named package. Code in a named package has no way to refer to it. This is one reason real projects always use named packages.
Why prefer single-type imports
Single-type imports have three practical advantages:
- Each import documents a dependency. A reader can see which classes the file uses and from where.
- They give priority over same-package classes and wildcard imports, so adding a class elsewhere cannot silently change what your name means.
- A missing or renamed class fails at the import line, which is a clear place to look.
The cost is more lines at the top of the file. IDEs add, sort, and remove them for you, so that cost is small. The next chapters compare this with wildcard imports.
Summary table
| Situation | Result |
|---|---|
| Import a class from another package | Simple name works in the whole file |
| Use a class from another package with no import | `cannot find symbol` unless you write the fully qualified name |
| Import `a.b.C` and use a class in `a.b.c` | Not included; subpackages are separate |
| Import the same class twice | Legal; the second is redundant |
| Import two classes with the same simple name | Compile error |
| Import a package-private class | Compile error: not public |
| Import a type from the default package | Not possible |
Exercise
A file in package com.example.shop contains import com.example.shop.model.Product; and also declares its own class named Product in the same file. Will it compile, and why or why not?
Show answer
It will not compile. A single-type import and a type declared in the same compilation unit cannot share a simple name, because the compiler could not tell which Product the simple name means. Remove the import and use the fully qualified name for the model class, or rename one of the classes.
Exercise
You change Main so it uses Product and Product.getName() but you delete the line import com.example.shop.model.Product;. You recompile with javac -d out src/com/example/shop/Main.java src/com/example/shop/model/Product.java. What does the compiler report, and give two ways to fix it.
Show answer
It reports cannot find symbol for the class Product, because Main is in a different package and nothing names Product for it. Fix it by restoring the single-type import import com.example.shop.model.Product;, or by writing the fully qualified name com.example.shop.model.Product at each use. Both produce the same bytecode.