当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Should an abstract class have at least one abstract method?

问题描述:

Is it necessary for an abstract class to have at least one abstract method?

网友答案:

The subject of this post and the body ask two different questions:

  1. Should it have at least one abstract member?
  2. Is it necessary to have at least one abstract member?

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 privateprotected constructor, not by marking it abstract.

网友答案:

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.

网友答案:

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)

网友答案:

If a class has an abstract modifier on its declaration it becomes abstract class.

分享给朋友:
您可能感兴趣的文章:
随机阅读: