【问题标题】:Can we access built-in classes without import statement我们可以在没有 import 语句的情况下访问内置类吗
【发布时间】:2014-06-25 14:04:57
【问题描述】:

我创建了一个类Exception(知道已经存在同名的内置子类)如下:

class Exception {
    public static void main(String args[]) {    
        int i=8;
        try{
            int a = args.length;
            int g = i/a;
        } catch(ArithemticException e){
            System.out.println("here is the error:"+e);
        }
    }
}


class Except7 {
    static int h;
    public static void main(String args[]) {
        try{
            int h = 9 / 0;
            System.out.println("//");
        } catch(ArithmeticException e) {
            h = 4;
            System.out.println(h);
        } catch(Exception e) {
            System.out.println("h");
        }
    }
}

您可能已经注意到,我在之前的代码中写了错误的“算术”拼写,所以编译器肯定会显示一个错误,它无法找到这个符号 (ArithemticException e)。 我所做的是,我没有在这里更改拼写,而是编写了另一个代码(后者)。在这里,我写了算术的正确拼写并尝试编译它。它给了我两个错误:

  1. incompatible types (required : Throwable found: Exception )
  2. cannot find symbol(ArithemticException.java)

我的疑问是:

  1. 我们怎么能这么容易地改变一个内置类(异常)?是因为它是一个抽象类吗?

  2. 即使我可以直接访问它(即不使用“import”语句),我也不倾向于更改异常的名称 (AritheticException)。我只是把它放在一个'catch'声明中。那么,为什么其他没有'import'语句的程序能够访问它。 (我也没有创建任何包,说它们是包保护的)

  3. 之前的程序没有被编译,还有其他程序出现“找不到符号”的错误。

【问题讨论】:

    标签: java


    【解决方案1】:

    我们怎么能这么容易地改变一个内置类(异常)

    你不能。

    发生的情况是您自己的类Exception 在没有任何显式导入语句的情况下被导入,因为它与Except7 在同一个包中。因此,在编译Except7 时,编译器使用yourPackage.Exception,而不是java.lang.Exception

    另见JLS: Chapter 7. Packages

    一个包由许多编译单元组成(第 7.3 节)。编译单元自动访问其包中声明的所有类型,并且还自动导入预定义包 java.lang 中声明的所有公共类型。

    另见String class make confusion

    【讨论】:

    • 好的。 !因此,它会进入我当前的目录,该目录的行为类似于我保存在那里的所有程序的默认包。
    • 是(准确地说,是“包”,而不是“目录”)。附带说明,不要使用默认包 - 始终将您的类放在具体包中。
    • 所以,实际上正在发生阴影!
    猜你喜欢
    • 2017-02-27
    • 1970-01-01
    • 1970-01-01
    • 2011-01-14
    • 1970-01-01
    • 2013-06-24
    • 2011-11-30
    • 2017-02-04
    • 1970-01-01
    相关资源
    最近更新 更多