[英]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. abstract
有其自己的目的。 If you want some of the class functionality implemented by other classes ( override
) then you use abstract. 如果你想要其他类( override
)实现的一些类功能,那么你使用abstract。
If it is just utility class, but you don't want other classes subclass it, then I would go with final
class. 如果它只是实用程序类,但你不希望其他类继承它,那么我会选择final
类。 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. 如果实用程序类只有static
方法,那么任何方法都不能覆盖它们,所以将它们放在non-final
类中也没有区别。
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
. final
这里比abstract
更有意义。 By marking the class as final
, you forbid the extending the class. 通过将类标记为final
,您禁止扩展类。 On the other hand marking the class as abstract
is kind of opposite, because abstract class without subclasses doesn't make much sense. 另一方面,将类标记为abstract
是相反的,因为没有子类的抽象类没有多大意义。 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) (这是像java.lang.Math
这样的类使用)
public final class A {
private A() {}
public static void method() {
}
}
如果你希望其他类使用这个类的功能,那么使它成为抽象的其他类使它成为最终
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; 如果要防止子类,请使用final作为类名; If you want to prevent instantiation, use a private constructor. 如果要阻止实例化,请使用私有构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.