Search code examples
javaclassabstractfinal

Java final abstract class


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?


Solution

  • Reference: Effective Java 2nd Edition Item 4 "Enforce noninstantiability with a private constructor"

    public final class MyClass { //final not required but clearly states intention
        //private default constructor ==> can't be instantiated
        //side effect: class is final because it can't be subclassed:
        //super() can't be called from subclasses
        private MyClass() {
            throw new AssertionError()
        }
    
        //...
        public static void doSomething() {}
    }