Reputation: 12744
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(){
/* ... */
}
}
Upvotes: 13
Views: 17901
Reputation: 41
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.
Upvotes: 1
Reputation: 34360
Best approach for creating Utility classes. If you don't want other classes to inherit it.
//final, because it's not supposed to be subclassed
public final class AlertUtils
{
// private constructor to avoid unnecessary instantiation of the class
private AlertUtils() {
}
public static ..(){}//other methods
}
Upvotes: 10
Reputation: 2721
Make the class final and add a private constructor. (This is what classes like java.lang.Math
use)
public final class A {
private A() {}
public static void method() {
}
}
Upvotes: 3
Reputation: 12837
final
here makes better sense than abstract
. By marking the class as final
, you forbid the extending the class. On the other hand marking the class as abstract
is kind of opposite, because abstract class without subclasses doesn't make much sense. So it is expected to be extended.
Upvotes: 4
Reputation: 46408
if you want other classes to use the functionality of this class then make it abstract else make it Final
Upvotes: 1
Reputation: 66637
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 just static
methods, any way you can't override them, so it doesn't make difference to have them in non-final
class also.
Upvotes: 12