[英]How can I make a protected static field public in sub class?
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
.我希望System.out.println(B.foo)
打印FOO
但它打印null
。
I know that I can get around this by replacing the field declaration in B
with a method like:我知道我可以通过用以下方法替换B
的字段声明来解决这个问题:
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.类 B 用作模拟对象,并添加这些括号以便调用B.foo()
而不是B.foo
并不重要,但我只是对是否可以摆脱它们感兴趣,如果是的,如果有充分的理由不这样做。 Or if my approach is completely wrong in some other way.或者,如果我的方法在其他方面完全错误。
I expect
System.out.println(B.foo)
to printFOO
but it printsnull
.我希望System.out.println(B.foo)
打印FOO
但它打印null
。
That is because B.foo
does not override A.foo
;那是因为B.foo
没有覆盖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.相反,它A.foo
- 换句话说, B.foo
是一个新变量,与A.foo
分开,恰好具有相同的名称。
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.不。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.