在什么情况下超类不应该是抽象的?
在这个线程中我发现了一些有趣的时刻,如果类使用仅作为超类,没有规则使其抽象。为什么会这样呢?
谢谢
In this thread I found some interesting moment, If class uses only as superclass there isn't rule to make it abstract. Why so?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这完全取决于拥有该类的实例是否有意义。
例如,假设您有一个类
Dog
和一个类Cat
。它们都扩展了Animal
。现在,Animal
可能有一个名称和一些方法,但是让Animal
到处跑是没有意义的。动物
是……一个抽象的概念。在其他情况下,您可能有子类(例如
LinkedHashSet
扩展了HashSet
),但实例化超类(HashSet
)仍然很有意义> 在这种情况下)。为了回答你的评论,“即使你不想实例化一个类,将它设为非抽象类是否有意义。”
好吧,我会说,如果你今天根本不这样做如果知道应该实例化它的任何用例,则适用相同的规则:拥有该类的实例是否有意义(逻辑上)?如果是这样,请将其设置为非抽象。
如果情况更像是“如果您创建了此类的实例,那么您可能做错了!”,那么我将通过使类抽象来澄清这一点。
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 classCat
. They both extendAnimal
. Now anAnimal
may have a name and a few methods, but it doesn't make sense to haveAnimal
s running around. AnAnimal
is... well an abstract notion.In other circumstances you may have subclasses (the
LinkedHashSet
for instance extendsHashSet
) 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.
来自 @aioobe - 考虑以下情况。
在公司中,您有一个名为会计师的职位。现在,假设您有一个专门从事审计的人,我们说他的头衔是审计员。现在,公司有100名会计师,但只有4名审计师。在这种情况下,您需要实例化Accountant和Auditor类,即使Accountant是一个超级类-审计员级别。
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.