虽然第一个示例编译,它会给出一个未选中的转换警告:
// Type safety: The return type List> for foo() from the type C needs
// unchecked conversion to conform to List
public List> foo()
{
return null;
}
这里发生的是,通过声明类型参数,A.foo()和B.foo()是generic methods.然后,覆盖的C.foo()省略该类型参数。这类似于使用raw type,基本上“选择退出”该方法签名的通用类型检查。这导致编译器使用继承的方法erasures:List< String> foo()和List< Integer> foo()都成为List foo(),因此可以通过C.foo()来实现。
您可以看到,通过在C.foo()声明中保留type参数,将会出现预期的编译器错误:
// The return type is incompatible with A.foo()
public List> foo()
{
return null;
}
同样,如果任何一个接口方法没有声明一个类型参数,那么从覆盖中省略一个类型参数将无法“选择退出”该方法的通用类型检查,返回类型List保持不兼容。
The notion of subsignature is designed to express a relationship between two methods whose signatures are not identical, but in which one may override the other. Specifically, it allows a method whose signature does not use generic types to override any generified version of that method. This is important so that library designers may freely generify methods independently of clients that define subclasses or subinterfaces of the library.
Now, let us explore an example where non-generic subtype methods
override generic supertype methods. Non-generic subtype methods are
considered overriding versions of the generic supertype methods if the
signatures’ erasures are identical.
Example (of non-generic subtype methods overriding generic supertype
methods):
06002
06003
Here the subtype methods have signatures, namely set(Object) and get()
, that are identical to the erasures of the supertype methods. These
type-erased signatures are considered override-equivalent.
There is one blemish in the case of the get method: we receive an
unchecked warning because the return types are not really compatible.
The return type of the subtype method get is Object , the return type
of the supertype method get is an unbounded type parameter. The
subtype method’s return type is neither identical to the supertype
method’s return type nor is it a subtype thereof; in both situations
the compiler would happily accept the return types as compatible.
Instead, the subtype method’s return type Object is convertible to the supertype method’s return type by means of an unchecked conversion. An unchecked warning indicates that a type check is necessary that neither the compiler nor the virtual machine can perform. In other words, the unchecked operation is not type-safe. In case of the convertible return types someone would have to make sure that the subtype method’s return value is type-compatible to the supertype method’s return type, but nobody except the programmer can ensure this.