12

Effective Java中,Joshua Bloch 更喜欢接口而不是抽象类。然而,他指出,每个接口都应该有一个框架实现。

我觉得骨架实现与抽象类几乎相同。这两个概念有何不同?

4

5 回答 5

6

在重新阅读有效 Java中的上述部分后编辑

根据本书的这一部分,骨架实现一个抽象类。他推荐这种方法,因为在框架实现到位之后,实现接口和选择性地覆盖方法变得微不足道,即使使用匿名类(正如他在书中所做的那样)。


上一个答案,为了连续性而略微编辑

一个骨架实现理论上可以是一个完整的实现,因此是具体的。然后它可以与composition一起使用,因为它可以被实例化。而抽象类需要继承。

于 2012-06-24T21:56:08.110 回答
4

What he means is that you should provide an interface, and an abstract class implementing parts of this interface:

public interface Foo {
    void bar();
    void baz();
}

private abstract class AbstractFoo implements Foo {
    ...
}

The AbstractFoo class may even not be abstract if it's possible to provide a basic, complete implementation. But if you need a class that is a Foo, but can't extend AbstractFoo, it's still possible with an interface. An abstract class doesn't provide this capability, since you can only extend one class.

BTW, this is what is done in the collections framework (which Josh Bloch created): the Set interface is implemented by AbstractSet, the List interface is implemented by AbstractList, etc.

于 2012-06-24T22:00:52.787 回答
2

The interface / abstract class is part of the API.

The skeletal implementation is a valid concrete class, but a limited / naïve / poor implementation; for (a very contrived) example, a skeletal implementation of a Sorter interface might implement bubble sort - you wouldn't want to use it in a production application, but it illustrates how one might implement the interface

于 2012-06-24T22:00:15.403 回答
2

我觉得骨架实现与抽象类几乎相同。这两个概念有何不同?

对我来说,他们的意图不同。当我看到某个方法需要传入一个接口时,我知道实现取决于我。如果返回一个类,我不再确定。使用一个类不存在的接口只是有意义的。

此外,当我们想要传入的类已经是子类时,接受类作为参数的方法会引发冲突;Java 不支持多重继承。接口没有这个问题。

于 2012-06-24T23:50:59.353 回答
0

“骨架实现”是一个具体的类:您可以编译和测试它。

抽象类不是,你不能;)

于 2012-06-24T21:55:59.613 回答