JavaCompiler didn't catch error on redefinition of a Java class.

58 Views Asked by At

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.

1

There are 1 best solutions below

0
MPluess On

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?