A package consists of a number of compilation units (§7.3). A compilation unit automatically has access to all types declared in its package and also automatically imports all of the public types declared in the predefined package java.lang.
Lets assume the following code:
package com.example.p1;
public class MyClass { }
package com.example;
public class MyClass { }
package com.example;
public class String { }
package com.example;
import com.example.p1.*;
public class MainNameClash {
private String s; // No Error, even though ambiguous with java.lang.String!
private MyClass m; // No error, even though ambiguous with com.example.p1.MyClass!
}
If I move MyClass
from com.example
into com.example.p2
and import it with import com.example.p2.*
, I get Error: the type MyClass is ambigious
at the place where it is used.
It seems that the Types from the package itself always have precedence over any other imported types, be it automatically from java.lang
or be it explicitly with a wildcard import, and that the compiler does not emit any warning or error.
Question:
- Why does the java compiler not emit an ambiguity error in this case?
- Where in the JLS is this behavior defined?
The import statements of the form:
is Type-Import-on-Demand Declarations. i.e, the classes or any types from them will be imported only when that type is not available in the scope of current compilation unit.
From example 7.5.2-1 of that JLS section only:
So, if you have a class
String
in the same package as your class, then usingString
in that class, will refer to your class, asjava.lang.String
will not be imported. It will only be imported on demand, as shown in example 6.4.1-2 of JLS § 6.4.1 - Shadowing.Actually the issue is about simple type names:
About scope we can read here:
..
I think this is covered in Shadowing & Obscuring in that a package scoped Class takes precedence over a wildcard import.