1

I have this code:

class A {
    protected static final String foo = "FOO";
}

class B extends A {
    public static final String foo;
}

I expect System.out.println(B.foo) to print FOO but it prints null.

I know that I can get around this by replacing the field declaration in B with a method like:

class B extends A {
    public static final String foo() { return foo; }
}

Is it possible to inherit a protected static field and make it public?

The class B is used as a mock object, and adding those parenthesis so the call is B.foo() instead of B.foo does not really matter, but I was just interested if it was possible to get rid of them, and if yes, if there is a good reason not to do that. Or if my approach is completely wrong in some other way.

Spyros K
  • 2,480
  • 1
  • 20
  • 37
klutt
  • 30,332
  • 17
  • 55
  • 95

1 Answers1

3

I expect System.out.println(B.foo) to print FOO but it prints null.

That is because B.foo does not override A.foo; instead, it shadows A.foo - in other words, B.foo is a new variable, separate from A.foo, that just happens to have the same name.

Variables cannot be overridden, and static methods cannot be overridden.

Only non-static methods can be overridden in a subclass.

Is it possible to inherit a protected static field and make it public?

No.

Jesper
  • 202,709
  • 46
  • 318
  • 350