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?
If you declare a method in a class abstract to use it, you must override this method in the subclass. But, overriding is not possible with static methods. Therefore, an abstract method cannot be static.
The only way to access the non-static method of an abstract class is to extend it, implement the abstract methods in it (if any) and then using the subclass object you need to invoke the required methods.
Yes, abstract class can have Static Methods. The reason for this is Static methods do not work on the instance of the class, they are directly associated with the class itself.
What is Utility Class? Utility Class, also known as Helper class, is a class, which contains just static methods, it is stateless and cannot be instantiated. It contains a bunch of related methods, so they can be reused across the application.
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.
}
}
Although a top-level class can't be declared static
, you can make the class non-instantiable (and practically 'static') to other classes by declaring the default constructor private
, which forbids instantiation because no constructor is visible.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With