简体   繁体   中英

Should a class with only static methods be abstract?

I have a class that offers a collection of static utility-type methods.

On the one hand, I don't want the class to be able to be instantiated. On the other hand, I don't want to send the signal that the class should be inherited from (not that I think that it's likely).

Should this class be abstract or not?

make the class final and make the default constructor private and do not provide any public constructors. that way no one can subclass it or create an instance of it.

Don't declare it abstract ; declare a private constructor, so no one, not even a subclass, can instantiate an instance of your utility class.

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

To borrow the idea from Pshemo's comment in another answer, throw a RuntimeException in the constructor to prevent reflection's setAccessible method in AccessibleObject from allowing instantiation:

public class MyUtility
{
   private MyUtility()
   {
      throw new RuntimeException("Instantiation of MyUtility is not allowed!");
   }

   public static void utilityMethod()
   {
      // Your utility method here.
   }
}

尽管顶级类不能声明为static ,但您可以通过声明默认构造函数private来使该类不可实例化(并且实际上是“静态”)到其他类,这禁止实例化,因为没有构造函数可见。

Another version of @mre's answer

enum MyClass{
    ;//this semicolon indicates that this enum will have no instances

    //now you can put your methods
    public static void myMethod(){
        //...
    }
}

Enum by default is final and its constructor is private. Also you cant create its instance with reflection because it checks in Constructor#newInstance if you are trying to instantiate Enum object.

What is contained in a class has no bearing on whether it should be abstract. The key take away: an abstract class must have another class extending it (a 'concrete' class); only that concrete class can be instantiated.

To prevent it from being extended, use final .

To prevent it from being instantiated, make the constructor private .

Observe that in Java these are discrete concepts.

No, it is a utility class.
It should be final with a private default constuctor, to avoid instantiation. If you have checkstyle enabled you would get a warning if you dont do it.

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

public final class Utils
{
    // prevent accidental construction.
    private Utils() 
    {  
    } 

    public static void foo()
    { 
        //util code here
    }
}

Seriously, you don't have to do anything . Nothing bad will happen, nobody is going to instantiate/subclass your class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM