Reputation: 140328
Consider the following code:
import java.util.Calendar;
class Demo
{
class Calendar {}
public static void main (String[] args) {
// System.out.println(Calendar.DAY_OF_WEEK); // Would be an error.
}
}
This code compiles fine; but if you refer to Calendar
within Demo
, you are referring to Demo.Calendar
, not java.util.Calendar
.
The import is clearly redundant; but it seems strange that it is allowed, considering you're not allowed to import a class with the same simple name as a top-level class defined in the same compilation unit (per JLS Sec 7.5.1):
import java.util.Calendar; // error: Calendar is already defined in this compilation unit
class Calendar {}
Is there a practical reason why such an import as in the first code example would not be a compile-time error?
Upvotes: 3
Views: 279
Reputation: 695
I suppose, if you import a class, it's visible in the global space of that compilation unit. But if you name your compilation unit or top level class the same as the import, then you are basically conflicting it with the import and hence it'll be ambiguous for JVM to know which is which. and since its compiling a class, it'll give an error for import.
Also, when it's inside another class, you are shadowing the import over there. It's just similar in the way as global/class level variables and method level variables hiding them if defined with the same name.
Hope this helps.
Upvotes: 0
Reputation: 140328
The only case I can come up with is where you have a twice (or more) -nested class with the same name as the import:
import java.util.Calendar;
class Demo {
static class Nested {
static class Calendar {}
static void useNested() {
System.out.println(Calendar.class); // Demo.Nested.Calendar
}
}
static void useImported() {
System.out.println(Calendar.class); // java.util.Calendar
}
public static void main(String[] args) {
Nested.useNested();
useImported();
}
}
In this case, the nested Calendar
isn't automatically visible outside the scope of the Nested
class, so the imported Calendar
class is used outside, e.g. in the useImported
method.
I wouldn't really describe this as a "practical" use, though - it's just plain confusing as to which is used in each context, and definitely worth avoiding. It still interested me that this case exists, though.
I suppose there is another similar case:
import java.util.Calendar;
class Demo {
static void useImported() { ... }
}
class Demo2 {
class Calendar {}
static void useNested() { ... }
}
(where these classes are in the same compilation unit). Basically the same idea as above.
Upvotes: 3