Pankaj
Pankaj

Reputation: 5250

Compiler error but program executes fine

I am confused with below code, Eclipse shows compiler error as "This static method cannot hide the instance method from Super" but when executed it works fine.

package com.journaldev.java;

public class Test {

    public static void main(String[] args) {
        Super s = new Subclass();
        s.foo();
    }
}

class Super {
    void foo() {
        System.out.println("Super");
    }
}

class Subclass extends Super {
    static void foo() {
        System.out.println("Subclass");
    }

}

See the output in below image, can someone clarify this?

Why Program Runs even though Compiler Error?

Upvotes: 2

Views: 1205

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503649

Eclipse allows you to run "most" of your code even when it won't all compile properly - although it usually prompts you. Typically the code that doesn't compile just throws an exception to indicate that compilation failed.

In this case, you never end up calling Subclass.foo, so you don't see the compilation error exception.

If you change the first line of main to:

Subclass s = new Subclass();

... then it will attempt to call the broken method, and you'll get output like this:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    This static method cannot hide the instance method from Super

    at sandbox.Subclass.foo(Test.java:18)
    at sandbox.Test.main(Test.java:7)

Personally I would strongly advise you to hit "Cancel" when you try to run something and Eclipse tells you there's a compile-time error with it. If you've previously clicked on "Always launch without asking" you need to go into your preferences and under "Launching" change "Continue launch if project contains errors" from "Always" to "Prompt". (The text may have changed; I'm using a fairly old version of Eclipse.)

Upvotes: 6

Related Questions