Why can final constants in Java be overridden?

Yuval Adam picture Yuval Adam · Oct 15, 2008 · Viewed 21k times · Source

Consider the following interface in Java:

public interface I {
    public final String KEY = "a";
}

And the following class:

public class A implements I {
    public String KEY = "b";

    public String getKey() {
        return KEY;
    }
}

Why is it possible for class A to come along and override interface I's final constant?

Try for yourself:

A a = new A();
String s = a.getKey(); // returns "b"!!!

Answer

Bill K picture Bill K · Oct 15, 2008

You are hiding it, it's a feature of "Scope". Any time you are in a smaller scope, you can redefine all the variables you like and the outer scope variables will be "Shadowed"

By the way, you can scope it again if you like:

public class A implements I {
    public String KEY = "b";

    public String getKey() {
        String KEY = "c";
        return KEY;
    }
}

Now KEY will return "c";

Edited because the original sucked upon re-reading.