java - 静态方法的 protected 修饰符的目的是什么

标签 java oop static-methods protected

我发现了 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/

相关文章:

java - Postgres-PreparedStatement 中的列超出范围-java

java - "Delete Where"在 Hibernate 中级联删除?

java - Tomcat Web 应用程序无法在网络上写入文件

java - 为什么 View 的操作(在本例中为按钮)必须采用 View 作为参数?

javascript - js继承和原型(prototype)赋值

Java 方法已损坏

java - 从 Java 中的通用静态方法获取类名

python - 指向 Python 中静态方法的指针

java - Java 中的空指针异常和作用域

php - 在哪里对数据进行计算 : in an object or in the database?