我发现了 protected
的这种用法为我的其他问题寻找解决方案时的修饰符:Ignoring case in strings with unitils ReflectionComparator
在org.unitils.reflectionassert.ReflectionComparatorFactory
类有一个带有签名的方法:
protected static List<Comparator> getComparatorChain(Set<ReflectionComparatorMode> modes)
但这只是特例。
毕竟我们总是可以扩展这样的任何非最终类并“覆盖”它是静态的 protected
新方法 public
修饰符。说,我们有一个类 A
:
public class A {
protected static void test() {
// do some stuff
}
}
并想在另一个包中使用它:
public class UseA {
private static class MyA extends A {
public static void test() {
A.test();
}
}
void useA() {
// A.test(); compile error, sure
MyA.test();
}
}
当一些 static
时,我将问题集中在一般情况上方法声明为 protected
.我不是在问非静态字段或方法,因为在某些情况下,类可以有一个私有(private)构造函数或一个非常复杂的构造函数,有很多特殊参数。但是,如果整个类不是 final
,那么这种“隐藏”静态方法的目的是什么? ?这种用法是 OOP 错误还是只是非常薄弱的“保护”?
最佳答案
But what is the purpose of such "hiding" static methods if entire class isn't final?
protected static
方法允许您向派生类提供“实用程序”类型的功能,而无需将它们暴露在公共(public) API 中,因为它们本身可能没有意义。
我不知道你引用的getComparatorChain
方法的实现,但我想是这样的方法。如果它不绑定(bind)到任何特定实例,它将被标记为 static
,并标记为 protected
以便不成为公共(public) API 的一部分,但也允许派生类在它自己的实现中重新使用实用程序方法。
关于java - 静态方法的 protected 修饰符的目的是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29772724/