简体   繁体   English

如何在子类中公开受保护的静态字段?

[英]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 print FOO but it prints null .我希望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.

相关问题 我怎样才能只获得java类的受保护的公共构造函数? - How can I get only protected and public constructors of a java class? 我可以在Java中嵌套的公共静态抽象类中读取公共静态最终字段吗 - can I read public static final field inside a nested public static abstract class in Java 使用其他类的公共静态HashTable的同步方法。 如何使该方法线程安全? - synchronized method that use a public static HashTable from other class. How can I make this method thread safe? 如何在类中引用最终静态字段的值? - How can I reference the value of a final static field in the class? 如何在我的示例中模拟一个具有静态字段的类? - How can I mock a class that has a static field in my example? 如何从 Java 应用程序中的另一个类访问在实用程序类中声明的公共最终静态列表? - How can I access to a public final static list declared into an utility class from another class in a Java application? 无法访问子 class 中的受保护方法 - Can not access protected method in the sub class 我可以使用Java公开受保护的成员吗? 我想从子类访问它 - Can I make a protected member public in Java? I want to access it from a subclass 我如何从另一个包中实例化Java内部的public static final类 - How can I instantiate a inner public static final class in java from a different package 如何从ColdFusion访问Java类的公共静态成员? - How can I access a public static member of a Java class from ColdFusion?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM