问题描述
我经常发现自己将类中的常见行为提取到仅包含一组静态方法的帮助程序/实用程序类中.我经常想知道我是否应该将这些类声明为抽象类,因为我真的想不出实例化这些类的正当理由?
I commonly find myself extracting common behavior out of classes into helper/utility classes that contain nothing but a set of static methods. I've often wondered if I should be declaring these classes as abstract, since I can't really think of a valid reason to ever instantiate these?
将这样的类声明为抽象类有什么优点和缺点.
What would the Pros and Cons be to declaring such a class as abstract.
public [abstract] class Utilities{
public static String getSomeData(){
return "someData";
}
public static void doSomethingToObject(Object arg0){
}
}
推荐答案
你可以只声明一个什么都不做的私有构造函数.
You could just declare a private constructor that does nothing.
将类声明为抽象"的问题在于抽象关键字通常意味着该类旨在被子类化和扩展.这绝对不是你想要的.
The problem with declaring the class "abstract" is that the abstract keyword usually means that class is intended to be subclassed and extended. That's definitely not what you want here.
这篇关于Helper/Utility 类应该是抽象的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!