Utility Class - What is the correct approach?
对于具有所有带有公共静态方法的实用程序类,正确的方法是什么?
我应该使用最终班还是抽象班?
请给个建议。
例如:
1 2 3 4 5 | public final class A{ public static void method(){ /* ... */ } } |
要么
1 2 3 4 5 | public abstract class A{ public static void method(){ /* ... */ } } |
如果它只是实用程序类,但是您不希望其他类将其子类化,那么我将使用
Best approach for creating Utility classes. If you don't want other classes to inherit it.
1 2 3 4 5 6 7 8 9 10 | //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 } |
将类定型并添加一个私有构造函数。 (这是像
1 2 3 4 5 6 | public final class A { private A() {} public static void method() { } } |
如果您想让其他类使用该类的功能,则使其抽象,否则使其成为Final
这些是我发现的一些准则:
- 所有方法都必须是公共静态的,以便它们不能被覆盖。
- 构造函数必须是私有的,这样可以防止实例化。
- 该类的final关键字可防止子类化。
- 类不应具有任何非最终或非静态的类字段。
如您所问,类名不能是抽象的(不建议使用)->这意味着您打算在另一个类中实现它。如果要防止子类化,请使用final作为类名。如果要防止实例化,请使用私有构造函数。