【问题标题】:Why does Java allow the name of the class to be same as that of a class it imports?为什么Java允许类的名称与它导入的类的名称相同?
【发布时间】:2015-11-26 07:16:33
【问题描述】:

我有以下代码:

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

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

【问题讨论】:

  • 它正在我的系统上编译

标签: java class naming


【解决方案1】:

为什么这个程序编译时会使用两个实际上同名的类?

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

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

不能抛出Exception类型的异常;异常类型必须是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");
        }
    }
}

【讨论】:

    【解决方案2】:

    Java 允许不同包中的类名相同。

    在你的例子中:

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

    java.lang.Exceptionjava.lang 包中。

    这就是为什么如果你尝试在同一个类中创建相同的类名然后编译器会显示错误。

    【讨论】:

      【解决方案3】:

      Java 编译器仅在您使用关键字作为“标识符”时才会抱怨。

      在java中,同名类可以重新声明,但只有约束,必须在不同的包中。

      这里,在你的情况下,

      你的类名 编译器允许的异常,因为它驻留在 不同的包而不是 java.lang。

      所以,在编译时,

      编译器只是检查同一个类是否在同一个包中。如果 发现然后编译器抱怨,已经存在否则不会。

      【讨论】:

        猜你喜欢
        • 2013-12-10
        • 1970-01-01
        • 1970-01-01
        • 2011-09-13
        • 2013-11-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多