Java Reference
In-Depth Information
It is not an error to use an import declaration to import types from
java.lang
package. They will be simply
ignored by the compiler. The following code will compile without errors:
package p1;
import java.lang.*; // Will be ignored because it is automatically done for you
public class G {
String anythingGoes; // Refers to java.lang.String
}
You need to be careful when using the simple name of a type, which is the same as a type that is defined in the
java.
l
ang
package. Suppose you declare a
p1.String
class.
// String.java
package p1;
public class String {
// Code goes here
}
Suppose you have a
Test
class in the same package,
p1.
// Test.java
package p1;
public class Test {
// Which String class will be used: p1.String or java.lang.String
String myStr;
}
Which
String
class is referred in the
Test
class:
p1.String
or
java.lang.String
? It will refer to
p1.String
,
not
java.lang.String
, because the package of the compilation unit (which is
p1
in this case) is searched before any
import declarations to resolve the simple names of types. The compiler finds the
String
class in package
p1
. It will not
search
java.lang
package for the
String
class. If you want to use the
java.lang.String
class in the above code, you
must use its fully qualified name, as shown:
// Test.java
package p1;
public class Test {
java.lang.String s1; // Use java.lang.String
p1.String s2; // Use p1.String
String s3; // Will use p1.String
}
Static Import Declarations
A static import declaration does what its name suggests. It imports
static
members (
static
variables/methods) of a
type into a compilation unit. You learned about
static
variable (or class variable) in previous sections. I will discuss
static
methods in the next section.