Should a base class be marked abstract if there ar

2019-05-07 10:17发布

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)

5条回答
一纸荒年 Trace。
2楼-- · 2019-05-07 10:28

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.

查看更多
Luminary・发光体
3楼-- · 2019-05-07 10:30

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.

查看更多
家丑人穷心不美
4楼-- · 2019-05-07 10:33

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 marked private. 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 its static methods. (This is a tip from Effective Java, by Josh Bloch)

查看更多
冷血范
5楼-- · 2019-05-07 10:44

Yes, I think so. At least that's what I do from time to time ;-)

查看更多
爷、活的狠高调
6楼-- · 2019-05-07 10:46

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.

  • It enforces the common guideline to make non-leaf classes abstract.
  • It prevents other programmers from creating instances of the class. This may make it easier for you to add abstract methods to it later.
查看更多
登录 后发表回答