为什么 Java 允许 class 的名称与它导入的 class 的名称相同?

Why does Java allow the name of the class to be same as that of a class it imports?

我有以下代码:

class Exception
{
    public static void main(String args[])
    {

        int x = 10;
        int y = 0;

        int result;

        try{
            result = x / y;
        }
        catch(ArithmeticException e){
            System.out.println("Throwing the exception");
            throw new ArithmeticException();
        }
    }
}

class 的名称是 'Exception'。这与默认导入到程序中的 java.lang.Exception 相同。那为什么这个程序编译时有两个 class 同名的?

Why does this program compile with two classes having effectively the same name?

它们具有相同的简单名称。但是,它们的名称(包括包声明的完全限定名称)不同。

按照您定义它的方式,您的代码无法编译,除非您的 class 位于项目的默认包中。您的类型 (Exception) 隐藏了 java.lang 包中定义的类型,并且由于您的类型不是 Throwable 的子类型,编译器会引发错误:

No exception of type Exception can be thrown; an exception type must be a subclass of Throwable

如果要指定 java.lang.Exception 应该被捕获,则必须使用完全限定名称,否则会发生命名冲突:

class Exception {
    public static void main(String args[]) {

        int x = 10;
        int y = 0;

        int result;

        try {
            result = x / y;
        } catch (ArithmeticException e) {
            System.out.println("Throwing the exception");
            throw new ArithmeticException();
        } catch (java.lang.Exception ae) {
            System.out.println("Caught the rethrown exception");
        }
    }
}

Java 允许 class 在不同的包中使用相同的名称。

在你的例子中:

Exception class 在您的应用程序的默认包中。

java.lang.Exceptionjava.lang 包中。

这就是为什么如果您尝试在相同的 class 中创建相同的 class 名称,那么编译器会向您显示错误。

Java 编译器仅在您将关键字用作 "identifier".

时才会报错

在java同名class你可以重新声明但唯一的限制是,它必须在不同的包中。

在这里,在你的情况下,

you class name Exception allowed by compiler because it reside into different package rather then java.lang.

因此,在编译时,

compiler just checks whether same class into same package or not. If found then compiler complain like, already exist otherwise won't.