爲什麼下面的代碼片段編譯? OtherInterface
不延伸Concrete
所以我會打賭腎不會編譯。但它確實如此。顯然類型違規,但編譯
public class Test {
public static interface SomeInterface {}
public static interface OtherInterface{}
public static class Concrete implements SomeInterface {
public <T extends Concrete> T getConcrete() {
return null;
}
}
public static void doStuff() {
Concrete c = new Concrete();
OtherInterface iCompile = c.getConcrete();
}
}
另一方面,下一個片段不編譯,這是我所期望的。
public class Test {
public static interface SomeInterface {}
public static class UnrelatedClass{}
public static class Concrete implements SomeInterface {
public <T extends Concrete> T getConcrete() {
return null;
}
}
public static void doStuff() {
Concrete c = new Concrete();
UnrelatedClass iCompile = c.getConcrete();
}
}
@azurefrog第二個不爲我編譯(我不是OP),錯誤消息是他'T'(它是'Concrete')的上限與'UnrelatedClass'不匹配。 – Tom
@azurefrog,湯姆的評論是我有 – Jerome
編譯的可能是在這個問題相同:https://stackoverflow.com/questions/29670018/why-can-this-generic-method-with-a-束縛返回任何類型。編譯器推斷一個交集類型'Concrete&OtherInterface'。 – Radiodef