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 have everything important within one separate class)...
This class should neither be instantiated, nor being extended. That made me write:
final abstract class MyClass {
static void myMethod() {
...
}
... // More private methods and fields...
}
(though I knew, it is forbidden).
I also know, that I can make this class solely final and override the standard constructor while making it private.
But this seems to me more like a "Workaround" and SHOULD more likely be done by final abstract class...
And I hate workarounds. So just for my own interest: Is there another, better way?
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:
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.
You can't get much simpler than using an
enum
with no instances.This class is final, with explicitly no instances and a private constructor.
This is detected by the compiler rather than as a runtime error. (unlike throwing an exception)
No, abstract classes are meant to be extended. Use private constructor, it is not a workaround - it is the way to do it!