鉴于为什么泛型类型Test2
类不默认为Base
类,而是默认为java.lang.Object
类的代码Java的通配符默认为java.lang.Object继承,而不是上限
abstract class Base<Thistype extends Base>
{
public void addOnSomethingListener(Consumer<? super Thistype> action)
{}
public void foo()
{
System.out.println("foo");
}
}
class Simple<Thistype extends Simple> extends Base<Thistype>
{
}
class Test1 extends Simple<Test1>
{
}
class Test2 extends Simple
{
}
class Test
{
public static void main(String[] args)
{
Test1 test1 = new Test1();
Test2 test2 = new Test2();
test1.addOnSomethingListener(test ->
{
test.foo(); // VALID as "test" is of type "Thistype" which is "Test1".
});
test2.addOnSomethingListener(test ->
{
test.foo(); // INVALID as "test" is of type "Thistype" which is "java.lang.Object" instead of "Base" which is the upper bound.
});
}
}
?
我提供了上限,但似乎这是不相关的,如果使用通配符或根本没有泛型。
如果你问我,主函数中的代码应该能够被编译。
好的,但有什么方法可以将它默认为上限......就好像我没有错,它永远不会是其他任何东西,这也可以解决我的问题 – Wietlol
您可以添加另一个类:class UpperBounded扩展Simple {}'和使用它作为类型参数的'Test2'声明:'class Test2 extends Simple {}'。 –
syntagma
是的,但与Test1类相比没有区别。 – Wietlol