简体   繁体   中英

What is the purpose of protected modifier for static methods

I found such an usage of protected modifier while searching for a solution for my other question: Ignoring case in strings with unitils ReflectionComparator

In the org.unitils.reflectionassert.ReflectionComparatorFactory class there is a method with the signature:

protected static List<Comparator> getComparatorChain(Set<ReflectionComparatorMode> modes)

But this is only a particular case.

After all we can always extend such any non-final class and "override" it's static protected method with the new public modifier. Say, we have a class A :

public class A {
    protected static void test() {
        // do some stuff
    }
}

and want to use it in another package:

public class UseA {
    private static class MyA extends A {
        public static void test() {
            A.test();
        }
    }

    void useA() {
        // A.test(); compile error, sure
        MyA.test();
    }
}

I concentrate my question on a general situation when some static method was declared as protected . I'm not asking about non-static fields or methods, because in some cases class can have a private constructor or a very complicated constructor with lots special params. But what is the purpose of such "hiding" static methods if entire class isn't final ? Is such usage an OOP mistake or just a very weak "protection"?

But what is the purpose of such "hiding" static methods if entire class isn't final?

A protected static method would allow you to provide "utility" type functionality to derived classes, without exposing them in the public API where they might not make sense on their own.

I don't know the implementation of the getComparatorChain method you reference, but I imagine it's such a method. It would be marked static if it's not tied to any specific instance, and marked protected so as not to be a part of the public API, but also to allow derived classes to re-use the utility method in it's own implementation.

Overriding a static method reference means hiding it's implementation. See: Java Documentation's Overriding and Hiding Methods

Static Methods

If a subclass defines a static method with the same signature as a static method in the superclass, then the method in the subclass hides the one in the superclass.

The distinction between hiding a static method and overriding an instance method has important implications:

  • The version of the overridden instance method that gets invoked is the one in the subclass.
  • The version of the hidden static method that gets invoked depends on whether it is invoked from the superclass or the subclass.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM