In Java, there are two valid forms of the import
declaration:
import java.lang.Math;
import java.lang.Math.*;
In the latter, a wildcard is used. This form is known as a Type-Import-on-Demand declaration, but how is it different from the former? Does it also import the subpackages of java.lang.Math
?
What if Math
were a Type (e.g., a class)—would all of its inner classes be imported?
The statement
imports all nested classes of ArrayList, but not ArrayList itself. Since ArrayList does not have any (public) nested classes, the statement actually does nothing.
However, consider the interface
Map
, which defines the nested classMap.Entry
. If we writeat the start of the Java file, we can then write
Entry<A,B>
instead ofMap.Entry<A,B>
to refer to this nested class.Importing members of classes usually makes the most sense if you are using static imports. Then you don't import nested classes, but static methods and variables. For example,
will import all static constants and methods from the
Math
class. Then you can use the static methods of theMath
class by writing, e.g.sin(x)
instead ofMath.sin(x)
.Basically Math is a final class, and it does not have further sub classes. There is no difference between
import java.lang.Math.*
andimport java.lang.Math
Both are one and the same. So I really dont see the need here to use the first kind of import.The documentation states:
So importing
import java.lang.Math.*;
will not import theMath
class.NOTE: You may also want to see Why is using a wild card with a Java import statement bad?
Only immediately-nested types are imported. The declaration is not recursive.
This does work with types for importing inner classes.This also works with static import (for importing methods).
import java.lang.Math.*;
This will import all nested classes declared in the
Math
class in thejava.lang
package. References to nested classes could be given without the outer class (e.g.,Foo
forjava.lang.Math.Foo
).import java.lang.Math;
This will import the
Math
class in thejava.lang
package. References to nested classes would have to be given with the outer class (e.g.,Math.Foo
).With the statement
import java.util.ArrayList.*;
you will import all nested classes declared intoArrayList
class.If you also want to import methods and const, for example, declares:
Then you can use the constant
PI
in your code, instead of referencing it throughMath.PI
, and the methodcos()
instead ofMath.cos()
. So, for example, you can write: