简体   繁体   中英

Utility Class - What is the correct approach?

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 just static methods, any way you can't override them, so it doesn't make difference to have them in non-final class also.

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
}

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.

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

如果你希望其他类使用这个类的功能,那么使它成为抽象的其他类使它成为最终

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.

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