berndbausch
berndbausch

Reputation: 845

Java packaging and import - where is my error?

Trying to learn Java from Bruce Eckel's book, I don't understand why the compiler doesn't find the library I want to import. I have first done this on Windows/Cygwin and now on Centos 7, using OpenJDK 1.8.0. Same result on both platforms.

This line:

import static t.b.u.*;

causes compiler error

$ javac TestPrint.java
TestPrint.java:2: error: package t.b does not exist
import static t.b.u.*;
                 ^

I agree that package t.b doesn't exist, but I actually wanted to import package t.b.u. Why does the compiler ignore the u?

CLASSPATH is set as follows:

$ export|grep CLASS
declare -x CLASSPATH="/home/bbausch/thinking-in-java"

The package is a single file:

$ cat /home/bbausch/thinking-in-java/t/b/u/Print.java

package t.b.u;
import java.io.*;

public class Print {
... etc ...

The error is probably so obvious that I don't see it. Can somebody help?

Upvotes: 0

Views: 44

Answers (1)

Compass
Compass

Reputation: 5937

This is specifically related to the Java Language Specification: https://docs.oracle.com/javase/specs/jls/se7/html/jls-7.html#jls-7.5.3

These two lines inherently ask for different things:

import static t.b.u.*;

This statement asks to import all static methods from a class named u from a package t.b.

import t.b.u.*;

This statement asks to import all classes underneath t.b.u.

Static imports target a TypeName only. Normal imports target a package, or a specific class.

The roughly equivalent general import to the static import would be this:

import t.b.u;

This asks to import just the class u from a package t.b.

In your specific example, you'd probably want this statement to import all static methods of the Print class.

import static t.b.u.Print.*;

Upvotes: 2

Related Questions