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?