Why we should not use protected static in java

前端 未结 8 2011
醉梦人生
醉梦人生 2020-11-29 17:01

I was going through this question Is there a way to override class variables in Java? The first comment with 36 upvotes was:

If you ever see a p

8条回答
  •  旧时难觅i
    2020-11-29 17:18

    I don't see a particular reason why this should be frowned upon. There may always be alternatives to achieve the same behavior, and it will depend on the actual achitecture whether these alternatives are "better" than a protected static method or not. But one example where a protected static method would be reasonable, at least, could be the following:

    (Edited to split into separate packages, to make the use of protected clearer)

    package a;
    import java.util.List;
    
    public abstract class BaseClass
    {
        public Integer compute(List list)
        {
            return computeDefaultA(list)+computeDefaultB(list);
        }
    
        protected static Integer computeDefaultA(List list)
        {
            return 12;
        }
        protected static Integer computeDefaultB(List list)
        {
            return 34;
        }
    }
    

    Derived from that:

    package a.b;
    
    import java.util.List;
    
    import a.BaseClass;
    
    abstract class ExtendingClassA extends BaseClass
    {
        @Override
        public Integer compute(List list)
        {
            return computeDefaultA(list)+computeOwnB(list);
        }
    
        private static Integer computeOwnB(List list)
        {
            return 56;
        }
    }
    

    Another derived class:

    package a.b;
    
    import java.util.List;
    
    import a.BaseClass;
    
    abstract class ExtendingClassB extends BaseClass
    {
        @Override
        public Integer compute(List list)
        {
            return computeOwnA(list)+computeDefaultB(list);
        }
    
        private static Integer computeOwnA(List list)
        {
            return 78;
        }
    }
    

    The protected static modifier can certainly be justified here:

    • The methods can be static, because they do not depend on instance variables. They are not intended to be used directly as a polymorphic method, but rather are "utility" methods that offer default implementations that are part of a more complex computation, and serve as "building blocks" of the actual implementation.
    • The methods should not be public, because they are an implementation detail. And they can't be private because they should be called by the extending classes. They also can't have "default" visibility, because then they will not be accessible for the extending classes in other packages.

    (EDIT: One could assume that the original comment only referred to fields, and not to methods - then, however, it was too general)

提交回复
热议问题