Why can you import a class with the same name as the nested class?

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

inside Demo

, you mean Demo.Calendar

, not java.util.Calendar

.

The import is clearly redundant; but it seems strange that this is allowed, given that you are not allowed to import a class with the same simple name as the 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 imports like the first code example wouldn't be a compile-time error?

+3


source to share


2 answers


The only case I can think of is where you have a twice (or more) -un-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();
  }
}

      

Ideone demo

In this case, the nested is Calendar

not automatically displayed outside the scope Nested

, so the imported class is Calendar

used outside, eg. in the method useImported

.

I wouldn't actually describe this as a "practical" use, but it is just confusing as to what is used in each context and should definitely be avoided. I was still interested in the existence of this case.




I assume 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.

+3


source


My guess is that if you import a class, it will show up in the global space of that compilation block. But if you name your compilation unit or top-level class the same as imports, then you basically contradict them with the imports and therefore the JVM will be ambiguous about what exactly. and after its compiling the class, it will give an error to import.

Also, when it's inside another class, you hide the import there. It's just like how globals and method level variables hide them when defined with the same name.



Hope it helps.

0


source







All Articles