4
    interface A
    {
        public void f();
        public void g();
    }


   class B implements A
   {
       public void f() 
       {
            System.out.println("B.f()");
       }
   }

   public class Main 
   {
       public static void main(String[] args) 
       {
            B tmp = new B();
            tmp.f();
            System.out.println("B.f()");
       }
   }

我没有在 B 中的接口 A 中实现所有方法,并且它有一个错误

    The type B must implement the inherited abstract method A.g()

但为什么它可以得到输出

    B.f()
    B.f()
4

2 回答 2

3

Eclipse 允许您运行带有编译时错误的代码 - 在给您一个警告并为您提供退出选项(您通常应该选择)之后。

如果您尝试调用tmp.g(),您将收到一个异常,指示编译时失败。

有时,运行未完全编译的代码可能很有用——特别是如果编译时失败与你实际希望运行的代码无关,例如在单元测试时——但我会非常小心你如何使用这个特性.

于 2013-08-05T07:52:21.313 回答
2

Eclipse 可以“修补”某些类别的编译错误,即使存在错误也可以运行程序。通常,您会看到一个对话框,其中包含以下内容:

所需项目中存在错误:

(项目名称)

继续发射?

[X] 总是不问就启动

如果您选择继续,或者如果您禁用了该对话框,Eclipse 将继续修复编译错误(如果可能)。如果您尝试运行受编译错误影响的代码,您将收到运行时异常。

在这种情况下,Eclipse 添加了一个虚拟B.g()方法,其中仅包含以下内容:

throw new java.lang.Error("Unresolved compilation problem: \n"
"The type B must implement the inherited abstract method A.g()");

通过插入这个虚拟方法,代码将正确编译并运行。如果你从不打电话B.g,那么你永远不会看到这个错误。

于 2013-08-05T08:15:05.203 回答