Java final abstract class

后端 未结 9 1971
情歌与酒
情歌与酒 2021-02-02 06:26

I have a quite simple question:

I want to have a Java Class, which provides one public static method, which does something. This is just for encapsulating purposes (to h

9条回答
  •  猫巷女王i
    2021-02-02 07:11

    The suggestions of assylias (all Java versions) and Peter Lawrey (>= Java5) are the standard way to go in this case.

    However I'd like to bring to your attention that preventing a extension of a static utility class is a very final decision that may come to haunt you later, when you find that you have related functionality in a different project and you'd in fact want to extend it.

    I suggest the following:

    public abstract MyClass {
    
        protected MyClass() {
        }
    
        abstract void noInstancesPlease();
    
        void myMethod() {
             ...
        }
        ... // More private methods and fields...
    
    }
    

    This goes against established practice since it allows extension of the class when needed, it still prevents accidental instantiation (you can't even create an anonymous subclass instance without getting a very clear compiler error).

    It always pisses me that the JDK's utility classes (eg. java.util.Arrays) were in fact made final. If you want to have you own Arrays class with methods for lets say comparison, you can't, you have to make a separate class. This will distribute functionality that (IMO) belongs together and should be available through one class. That leaves you either with wildly distributed utility methods, or you'd have to duplicate every one of the methods to your own class.

    I recommend to never make such utility classes final. The advantages do not outweight the disadvantages in my opinion.

提交回复
热议问题