Utility Class - What is the correct approach?

2019-02-06 19:43发布

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(){
        /* ... */
    }
}

标签: java class
6条回答
趁早两清
2楼-- · 2019-02-06 19:44

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.

查看更多
在下西门庆
3楼-- · 2019-02-06 19:44

if you want other classes to use the functionality of this class then make it abstract else make it Final

查看更多
ゆ 、 Hurt°
4楼-- · 2019-02-06 19:58

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() {
    }
}
查看更多
Deceive 欺骗
5楼-- · 2019-02-06 19:59

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.

查看更多
霸刀☆藐视天下
6楼-- · 2019-02-06 20:02

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
}
查看更多
Anthone
7楼-- · 2019-02-06 20:07

These are some guidelines I've found:

  • All methods must be public static, so that they cannot be overridden.
  • Constructor must be private, so it'll prevent instantiation.
  • Final keyword for the class prevents sub-classing.
  • Class should not have any non-final or non-static class fields.

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.

查看更多
登录 后发表回答