Imports: using classes from other packages¶
☕ Java 17 · Organizing Your Code with Packages and Imports · 2/3
Your classes now live in packages. To use a class from another package, you import it.
Single and wildcard imports¶
package com.netflix.platform;
import com.netflix.content.Movie; // one class
import com.netflix.content.*; // every class of the package
public class StreamingPlatform {
Movie featured;
}
| Import | Brings in | Notes |
|---|---|---|
import com.netflix.content.Movie; |
exactly Movie |
preferred: you see which classes are used |
import com.netflix.content.*; |
all classes directly in com.netflix.content |
not its sub-packages |
Classes in the same package don't need an import.
java.lang comes for free¶
String, System, Math, Integer live in java.lang, which every Java file imports automatically. You never write import java.lang.String;. It's allowed, just useless.
The order is fixed¶
A source file follows this order, always:
package com.netflix.content; // 1. package (if any)
import java.util.List; // 2. imports
public class Movie { // 3. class
List<String> genres;
}
An import before the package, or a class before the imports, is a compiler error.
Two classes with the same name¶
Importing both Movie classes doesn't work: Java can't tell which one Movie means.
import com.netflix.content.Movie;
import com.thirdparty.catalog.Movie; // ❌ compiler error: Movie is already imported
The fix: import one, and use the fully qualified name for the other.
import com.netflix.content.Movie;
public class Catalog {
Movie mine = new Movie();
com.thirdparty.catalog.Movie external = new com.thirdparty.catalog.Movie();
}
A fully qualified name works anywhere, even without any import.
You can now organize classes and connect them. The lab builds a small packaged project and runs it from the terminal.