Should a class with only static methods be abstract?

I have a class that offers a collection of static methods like utilities.

On the one hand, I do not want the class to be created. On the other hand, I do not want to send a signal that the class should be inherited (not the way I think it is possible).

Should this class be abstract or not?

+4
source share
8 answers

make the class final and make the default constructor private and not provide any public constructors. thus, no one can subclass it or create an instance from it.

+10
source

Do not declare it abstract ; declare the constructor private , so no one, not even a subclass, can instantiate your utility class.

You can declare your class final , although if all the constructors are private , then no one can subclass it anyway.

To borrow the idea from Pshemo's comment in another answer, throw a RuntimeException in the constructor to prevent the setAccessible method from reflecting AccessibleObject from resolving the instance:

 public class MyUtility { private MyUtility() { throw new RuntimeException("Instantiation of MyUtility is not allowed!"); } public static void utilityMethod() { // Your utility method here. } } 
+5
source

Although a top-level class cannot be declared static , you can make the class non-intuitive (and practically "static") for other classes by declaring the default constructor private , which prohibits instantiation, because there is no constructor.

+3
source

Another version of @mre answer

 enum MyClass{ ;//this semicolon indicates that this enum will have no instances //now you can put your methods public static void myMethod(){ //... } } 

Enum is final by default, and its constructor is private. Also, you cannot create your own instance with reflection, because it checks the constructor # newInstance if you are trying to instantiate an Enum object.

+2
source

What is contained in the class is irrelevant to whether it should be abstract. The key selects: the abstract class must have another class that extends it (the "concrete" class); only a specific class can be created.

To prevent its expansion, use final .

To prevent its creation, create a private constructor.

Note that in Java these are discrete concepts.

+1
source

No, this is a utility class.
It must be final with the private constructor constant to avoid instantiating. If you have checkstyle enabled, you will receive a warning if you do not.

+1
source

In addition to all the other challenges, in order to give a class a private constructor, you must also make it final so that it is clear that nothing can subclass it.

 public final class Utils { // prevent accidental construction. private Utils() { } public static void foo() { //util code here } } 
+1
source
Seriously, you don't have to do anything. Nothing bad will happen, no one is going to create / subclass your class.
+1
source

All Articles