java - 为什么Java允许类名与它导入的类名相同?

标签 java class naming

我有以下代码:

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();
        }
    }
}

类的名称是“Exception”。这与默认导入到程序中的 java.lang.Exception 相同。那么为什么这个程序编译时会使用两个实际上具有相同名称的类呢?

最佳答案

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

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

按照您定义的方式,您的代码无法编译,除非您的类位于项目的默认包中。您的类型(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 - 为什么Java允许类名与它导入的类名相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33932619/

相关文章:

java - 计算机视觉、C++ 或 Java

java - 如何配置 Tomcat 以使用 Java 7

java - logback中不同日志级别的不同日志文件

.net - 我可以使用强命名的 Ninject ConstructorArguments 吗?

java - 命名具有继承性的 Java 文件以进行编译

java - 如何使用JScrollBar缩放图像?

带有变量的 PHP 模板类?

ruby - 有没有办法让 Ruby 访问器返回 set 变量以外的东西?

c++ - 在 C++ 中创建非二叉树结构

python - Python 正则表达式的命名约定?