抽象类扩展了具体类 [英] Abstract class extends concrete class
问题描述
我之前了解到抽象类可以扩展具体类。虽然我没有从JAVA设计师那里看到它的原因,但它没问题。
我还了解到扩展具体类的抽象类可以使重写方法成为抽象。为什么?你能提供有用的用例吗?我正在努力学习设计模式,我不想错过任何东西。
I earlier learned that abstract class can extend concrete class. Though I don't see the reason for it from JAVA designers, but it is ok. I also learned that abstract class that extends concrete class can make overriden methods abstract. Why? Can you provide with use case where it is useful? I am trying to learn design patterns and I do not want to miss anything.
以下是示例:
public class Foo
{
public void test()
{
}
}
public abstract class Bar extends Foo
{
@Override
public abstract void test();
}
推荐答案
如果我有我希望默认实现 test()
的一组类(因此它们可以从 Foo
扩展),以及我想强制提供自己的实现的那些类的子集(在这种情况下,在子类中将其抽象化将强制执行此操作。)
This becomes useful if I have a set of classes that I want a default implementation of test()
for (so they can extend from Foo
), and a subset of those classes that I want to force to provide their own implementation (in which case making it abstract in the subclass would enforce this.)
当然,在这个例子中的替代方法是在顶级类而不是在子类中声明 test()
abstract,这就是你通常所做的 - 但是有些情况满足is-a继承关系的地方意味着从设计的角度来看它偶尔会更有意义。这种情况很少见,但有时你会看到它。
Of course, the alternative way in this example would be to declare test()
abstract in the top level class rather than in the subclass, and that's what you'd usually do - but there are cases where satisfying the is-a relationship of inheritance means that it occasionally makes more sense from a design perspective doing it this way around. It's rare, but you do sometimes see it.
顺便说一下,虽然是特殊情况,但请记住所有类都隐式扩展 Object
除非另有说明。因此,如果你包含这种情况,那么扩展具体类的抽象类毕竟不是那么罕见!
As an aside, though a special case, remember that all classes implicitly extend Object
unless otherwise specified. So if you include this case, abstract classes extending concrete classes isn't so unusual after all!
这篇关于抽象类扩展了具体类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!