0

During my Java learning, I tried this piece of code which compiled & ran successfully. Can anybody please provide an explanation that why hasn't the compiler generated any error? I imported the complete package which includes java.util>Scanner as well, so shouldn't there be an error that the Scanner is already defined in util package & I'm trying to redefine it here?

import java.util.*;

class Scanner
{
    public static void main(String... args)
    {
        Scanner c = new Scanner();
    }
}

My Java basics are not very clear so kindly bear if this appears to be completely a noob's question and there was no question alike on this forum so I thought to better ask it.

WhiteSword
  • 101
  • 9
  • 1
    Names in the current compilation unit takes precedence over anything imported with an on-demand import. It would have been an error if you'd imported `java.util.Scanner` explicitly. – Andy Turner Feb 15 '17 at 13:25
  • Add java.util.Scanner import, and you'll see it marked as not used – c0der Feb 15 '17 at 13:31
  • yeah, that way it does throw a compilation error. I just wanted to know that why doesn't it while importing the whole package. – WhiteSword Feb 15 '17 at 13:37

1 Answers1

-1

A class is not only defined by its name, but also by it's package.

In your case you have two different classes:

  • java.util.Scanner
  • your.package.Scanner (Sorry, your package line is not part of your code)

For the compiler, these classes are different and that's why no compile error appears.

For a longer answer with code examples and a possible use-case, have a look here: Importing two classes with same name. How to handle?

Community
  • 1
  • 1
MPluess
  • 1
  • 1