Java final abstract class

Sauer picture Sauer · Mar 8, 2012 · Viewed 37k times · Source

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?

Answer

Peter Lawrey picture Peter Lawrey · Mar 8, 2012

You can't get much simpler than using an enum with no instances.

public enum MyLib {;

   public static void myHelperMethod() { }
}

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)