0

How is the Comparable interface is marker interface, even though it defines a compareTo() method? Please explain detail.

4

3 回答 3

6

标记界面只是一种设计模式。因此,即使您阅读“X 是一个标记接口”,除了“X 是一个没有声明方法的接口”之外,这并没有真正的意义。

由于Comparable<T>只有一种方法,因此它不用作标记接口。

当您希望将数据附加到类型以便能够在特定情况下使用此数据时,标记接口很有用Comparable,而 用于提供有效接口的情况并非如此。

我什至不认为 javadoc 中使用标记接口的定义来描述空接口,例如Serializable(虽然不确定)。

于 2013-01-09T19:02:51.577 回答
1

它不是一个标记界面。Java 中的标记接口,例如 Serializable、Clonnable 和 Remote 用于向编译器或 JVM 指示某些内容;向编译器指示标志。

于 2013-01-09T19:07:41.513 回答
1

Quoting Wikipedia on Marker interface pattern (emphasis mine):

[...] class implements a marker interface, and methods that interact with instances of that class test for the existence of the interface. Whereas a typical interface specifies functionality (in the form of method declarations) that an implementing class must support, a marker interface need not do so. The mere presence of such an interface indicates specific behavior on the part of the implementing class. Hybrid interfaces, which both act as markers and specify required methods, are possible but may prove confusing if improperly used.

That being said Comparable<T> can be called a marker interface, but it's confusing and I've never heard this before.

I can't imagine a class testing whether some object implements Comparable<T> without actually down-casting and calling compareTo().

于 2013-01-09T19:09:54.507 回答