超类和子类都有自己的接口

时间:2012-01-19 14:04:25

标签: java design-patterns

以下是否可以? (请记住,我没有编写类的主体,我也没有编写接口; - ))

abstract class SuperClass implements SuperInterface

class SubClass extends SuperClass implements SubInterface

或者这通常被认为是不好的做法?

令我惊讶的是,以下不起作用:

List<SubInterface> myList;
...
for(SuperInterface si : myList) {
    ...
}

3 个答案:

答案 0 :(得分:10)

既不好也不坏。 SubClass此处实现了SuperInterfaceSubInterface(以及SuperClass'公共方法定义的接口)。如果那就是你需要的 - 那很好。

至于你的第二个例子

List<SubInterface> myList;
...
for(SuperInterface si : myList) {
    ...
}

您声明了SubInterface个元素的列表,但想要从中获取SuperInterface个元素。如果SubInterface延伸SuperInterface,那么这有一定意义。否则不会。

答案 1 :(得分:3)

这是对的。为什么不呢?

你的SuperClass实现了一个SuperInterface,它也由你的SubClass实现(感谢SubClass扩展了SuperClass)。

此外,您的SubClass实现了另一个接口(SubInterface)。

您的代码/架构没有任何问题。

SuperClass -- implements --> SuperInterface
SubClass -- extends --> SuperClass -- implements --> SuperInterface*, SubInterface
  • 由于SuperClass的扩展而产生的隐式工具

答案 2 :(得分:1)

这很好,取决于你想要实现的目标(你可能会有更好的设计),请记住SubClass是SuperInterface和SubInterface