抽象类应该至少有一个抽象方法吗?
抽象类是否必须至少有一个抽象方法?
Is it necessary for an abstract class to have at least one abstract method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
抽象类是否必须至少有一个抽象方法?
Is it necessary for an abstract class to have at least one abstract method?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(5)
这篇文章的主题和正文提出了两个不同的问题:
#2 的答案肯定是否定的。
第一个问题的答案是主观的并且是风格问题。我个人会说是的。如果您的目的是防止实例化类(没有抽象方法),则处理此问题的最佳方法是使用
private
protected
构造函数,而不是通过将其标记为抽象
。The subject of this post and the body ask two different questions:
The answer to #2 is definitively no.
The answer to #1 is subjective and a matter of style. Personally I would say yes. If your intent is to prevent a class (with no abstract methods) from being instantiated, the best way to handle this is with a
private
protected
constructor, not by marking itabstract
.不,没有必要。您经常会在“模板方法”设计模式中看到这一点,例如
HttpServlet
,其中每个方法已经具有默认行为已定义,您可以随意覆盖其中一个(或多个)而不是全部。HttpServlet
类仅仅是抽象
,以防止无意中使用new HttpServlet()
直接初始化,否则基本上会返回一个空的、未实现的且无用的servlet 实例。No, it is not necessary. You see this often back in "template method" design pattern, like
HttpServlet
, wherein each method already has default behaviour definied and you're free to override just one (or more) of them instead of all of them.The
HttpServlet
class is merelyabstract
to prevent direct initialization by inadvertendly usingnew HttpServlet()
which would otherwise basically have returned an empty, unimplemented and useless servlet instance.在 JDK 1.0 中,抽象类中确实需要至少有一个抽象方法。这个限制在 JDK 1.1(1997?(我老了))中被删除,并且此类类被添加到 Java 库中,例如
java.awt.event.KeyAdapter
。在 C++ 中,您至少需要一个纯虚函数来使子类成为必需,并且至少需要一个虚函数来将 RTTI 添加到类中。通常使用析构函数是有意义的。
请注意,当重写非抽象方法时,使用 @Override 是一个好主意。它不仅告诉读者有关代码尝试执行的操作的重要信息,而且还发现打字错误或不正确的参数类型阻止覆盖的常见错误。
In JDK 1.0 it was indeed necessary to have at least one abstract method in an abstract class. This restriction was removed in JDK 1.1 (1997? (I'm old)) and such classes added to the Java library, such as
java.awt.event.KeyAdapter
.In C++ you need at least one pure virtual function to make a subclass necessary, and at least one virtual function to add RTTI to the class. Typically it makes sense to use the destructor.
Note when overriding non-abstract methods, using
@Override
is a good idea. It not only tells the reader important information about what the code is attempting to do, but also spots common errors where typos or incorrect parameter types prevents the override.不 - 您可以声明一个抽象类,而无需任何抽象方法。从概念上讲,该类的实例存在可能没有任何意义,或者您可能希望确保只能实例化该类的子类(无论出于何种原因)
No - you can declare a class abstract without having any abstract methods. It may not make any sense conceptually for an instance of that class to exist, or you may want to ensure that only subclasses of that class can be instantiated (for whatever reason)
如果一个类在其声明中具有
abstract
修饰符,那么它就成为abstract
类。If a class has an
abstract
modifier on its declaration it becomesabstract
class.