Tại sao đoạn mã dưới đây biên dịch? OtherInterface
không mở rộng Concrete
vì vậy tôi sẽ đặt cược một quả thận rằng điều này sẽ không biên dịch. Nhưng nó có.Vi phạm loại hiển nhiên, nhưng biên dịch
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();
}
}
Mặt khác, đoạn mã tiếp theo không biên dịch, đó là những gì tôi mong đợi.
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 Điều thứ hai không biên dịch cho tôi (tôi không phải OP) và thông báo lỗi là anh ta gửi về 'T' (là' Concrete') không khớp với 'UnrelatedClass'. – Tom
@azurefrog, nhận xét của Tom là những gì tôi có – Jerome
Trình biên dịch có thể giống như trong câu hỏi này: https://stackoverflow.com/questions/29670018/why-can-this-generic-method-with-a- bound-return-any-type. Trình biên dịch gây ra một kiểu giao cắt 'Concrete & OtherInterface'. – Radiodef