« Home

Java 的 interface 與 bounded polymorphism (bounded quantification) [tt-000N]

在 Java 之中可以定義 interface,範例如下

interface Comparable {
  int compareTo(T other);
}

相較於 [Go 中不用明確宣告](tt-000D),在 Java 中實現 interface I 需要寫成 class T extends I,因此雖然 Java 的 interface AA 也有其相關的一組簽名 P^\hat P ,但兩個有同樣簽名 P^\hat P 的 interface 不是同一個型別。

而在 Java 中 bounded polymorphism 指的是以下的 interface 使用方法:

<S extends Comparable> S min(S a, S b)

這會使得沒有明確宣告實現 Comparable 的型別無法被傳為 min 的引數。