What is the correct approach for a utility class having all methods with public static.
Should I use final class or abstract class?
Please give suggestion.
As for example:
public final class A{
public static void method(){
/* ... */
}
}
OR
public abstract class A{
public static void method(){
/* ... */
}
}
abstract
has its own purpose. If you want some of the class functionality implemented by other classes (override
) then you use abstract.If it is just utility class, but you don't want other classes subclass it, then I would go with
final
class. If utility class has juststatic
methods, any way you can't override them, so it doesn't make difference to have them innon-final
class also.if you want other classes to use the functionality of this class then make it abstract else make it Final
Make the class final and add a private constructor. (This is what classes like
java.lang.Math
use)final
here makes better sense thanabstract
. By marking the class asfinal
, you forbid the extending the class. On the other hand marking the class asabstract
is kind of opposite, because abstract class without subclasses doesn't make much sense. So it is expected to be extended.These are some guidelines I've found:
As you've asked, the class name cannot be abstract (not advisable) -> Which means you are planning to implement it in another class. If you want to prevent sub-classing, use final for the class name; If you want to prevent instantiation, use a private constructor.