如果没有抽象成员,基类是否应该标记为抽象?
如果一个类没有抽象成员,可以将其标记为抽象吗?即使没有实际理由直接实例化它? (除了单元测试)
Is it okay for a class to be marked as abstract if it has no abstract members? Even if there is no practical reason for to directly instantiate it? (aside from unit tests)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
是的,将不应该实例化的基类显式标记为抽象是合理且有益的——即使在没有抽象方法的情况下也是如此。
Yes, it is reasonable and beneficial to mark explicitly as abstract a base class that should not be instantiated -- even in the absence of abstract methods.
您希望该类有一个实际的实例吗?如果是,则不要将其标记为抽象。如果不是,则将其标记为摘要。
Do you want that class to ever have an actual instance? If yes, then don't mark it abstract. If no, then mark it abstract.
简短的回答:是的。
长答案:
abstract
关键字将类和/或其成员标记为不直接有用。为什么会出现这种情况,具体情况可能有所不同;抽象类可能太基础而无法完成任何实际工作,或者它可能具有此类中其他代码工作所需的抽象成员,但无法在此级别具体定义。缺点是,通过标记类抽象,您可以告诉编译器和其他开发人员不要直接实例化该类,而是继承它以创建具体的有用实现。即使该类对其所有成员都有一个有效的实现,如果您认为必须继承该类才能充分利用该实现,您也可以执行此操作。Short answer: yes.
Long answer: The
abstract
keyword marks a class and/or its members as not being useful directly. Why this may be varies from case to case; an abstract class may be too basic to do any real work, or it may have abstract members that are required to exist for other code in this class to work, but cannot be concretely defined at this level. The short of it is that by marking a class abstract, you tell the compiler and other developers not to instantiate this class directly, but instead to inherit from it to create a concrete useful implementation. You can do this even if the class has a working implementation for all its members, if you feel that the class must be inherited to make the best use of that implementation.如果目标是创建一个可供其他类扩展的基类,则将其设为抽象类是有意义的。
但是,如果目标是创建某种形式的实用程序类(只有静态成员),则处理此问题的最佳方法是为该类提供一个标记为私有的构造函数。这样,该类就不能被实例化,也不能被子类化。这发出了一个明确的信号:该类的唯一用途是使用其静态方法。 (这是来自 Josh Bloch 的 Effective Java 的提示)
If the goal is to make a base class that other classes will extend, it makes sense to make this an abstract class.
If, however, the goal is to make some form of Utility class -- one that has only
static
members -- the best way to handle this is to give the class a single constructor markedprivate
. That way, the class can not be instantiated, nor subclassed. This sends a clear signal that the only use of the class is to use itsstatic
methods. (This is a tip from Effective Java, by Josh Bloch)是的,我想是的。至少我时不时就是这样做的;-)
Yes, I think so. At least that's what I do from time to time ;-)