假设我有这样的简单课程
public interface Something{
public void doSomtehing()
}
class A{
public int getAVal(){
return 0;
}
}
class AWithSomething extends A implements Something{
public void doSomething{
//in fact do nothing, HAHA
}
}
abstract class B{
public abstract <T extends A & Something> T getAWithSomething()
}
class C extends B{
//allowed??? gives warnig about unchecked conversion
public A getAWithSomething {
return new A();
}
}
class D extends B{
//same unchecked warning
public AWithSomething getAWithSomething(){
return new AWithSomething();
}
}
C c = new C();
//not implemented but seems valid
c.getAWithSomething().doSomething();
D d = new D();
d.getAWithSomething().doSomething();
所以我的主要问题是:为什么编译器允许类C
只返回一个 A 而不检查它是否在编译时实现接口?
编辑(由于 darijan 的评论):嗯,但我不允许这样声明:
class C extends B{
//not allowed!
public Something getAWithSomething {
return new Something(){
doSomething(){}
};
}
}