开发者

In what cases superclass shouldn't be abstract?

In this thread I found so开发者_StackOverflow社区me interesting moment, If class uses only as superclass there isn't rule to make it abstract. Why so?

Thanks


It all depends on whether or not it makes sense to have instances of the class.

Suppose you for instance have one class Dog and one class Cat. They both extend Animal. Now an Animal may have a name and a few methods, but it doesn't make sense to have Animals running around. An Animal is... well an abstract notion.

In other circumstances you may have subclasses (the LinkedHashSet for instance extends HashSet) but it still makes a lot of sense to instantiate the super class (HashSet in this case).


To answer your comment, "Does it make sense to make a class non-abstract even if you don't want to instantiate it."

Well I'd say if you, today, simply don't know of any use-cases in which it should be instantiated, the same rule applies: Does it make sense (logically) to have an instance of the class? If so, make it non-abstract.

If the situation is more like "If you've created an instance of this class, you're probably doing it wrong!" then I'd clarify this by making the class abstract.


Following from @aioobe - Think of the following situation.

In a company, you have a position called Accountant. Now, let's say that hypothetically you have someone that specializes in auditing, and we say his title is Auditor. Now, the company has 100 accountants, but only 4 Auditors. In this case, you would want to instantiate both the Accountant and Auditor classes, even though Accountant is a super-class of Auditor.


If the class is complete and usable it makes sense that you should be able to instantiate and use the class, even if the user decides to extend it later.

The class should only be abstract if the user needs to implement some logic to make it functional within the framework in which it is being used i.e. where the class designer does not know the exact implementation details of how the class will be used, like the template or command design patterns for example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜