如何在子类中将受保护的静态字段改为公共字段?

huangapple go评论64阅读模式
英文:

How can I make a protected static field public in sub class?

问题

我有这段代码:

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

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

我期望 System.out.println(B.foo) 输出 FOO,但实际上输出了 null

我知道可以通过在类 B 中将字段声明替换为方法来解决:

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

是否可能继承受保护的静态字段并将其变为公共的?

B 被用作模拟对象,添加括号使调用变为 B.foo() 而不是 B.foo 并不重要,但我只是想知道是否有可能摆脱这些括号,如果是,是否有充分的理由不这样做。或者如果我的做法在某些方面完全错误。

英文:

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.

答案1

得分: 3

我期望 System.out.println(B.foo) 输出 FOO,但实际上它输出了 null

这是因为 B.foo 没有重写 A.foo;相反,它遮蔽了 A.foo - 换句话说,B.foo 是一个新的变量,与 A.foo 分开,只是恰好具有相同的名称。

变量不能被重写,静态方法也不能被重写。

只有非静态方法可以在子类中被重写。

是否可能继承一个受保护的静态字段并将其变为公共的?

不可以。

英文:

> 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.

huangapple
  • 本文由 发表于 2020年9月23日 21:01:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/64028576.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定