CLS
CLS

Reputation: 131

why java can run with a compile time error in eclipse

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

I don't implement all the method in the interface A in B and it has a error that

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

but why it can get the output that

    B.f()
    B.f()

Upvotes: 4

Views: 1361

Answers (2)

nneonneo
nneonneo

Reputation: 179392

Eclipse can "patch" around certain classes of compile errors, and run a program even if errors exist. Normally, you get a dialog box that says the following:

Errors exist in required project(s):

(project name)

Proceed with launch?

[X] Always launch without asking

If you select Proceed, or if you have disabled the dialog, Eclipse will proceed to fix the compile errors if possible. If you try to run code impacted by the compile error, you'll get a runtime exception.

In this case, Eclipse adds a dummy B.g() method containing just the following:

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

By inserting this dummy method, the code will compile properly and it will run. If you never call B.g, then you'll never see this error.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500015

Eclipse allows you to run code with compile-time errors - after giving you a warning and offering you the option to back out (which you should normally take).

If you try to call tmp.g() you'll get an exception indicating a compile-time failure.

Occasionally it can be useful to run code which doesn't fully compile - particularly if the compile-time failure is unrelated to the code you actually wish to run, e.g. when unit testing - but I would be very careful about how you use this feature.

Upvotes: 3

Related Questions