Java:抽象类的具体方法的返回类型变为raw

时间:2017-07-14 21:38:52

标签: java generics unchecked-cast

以下代码在使用-Xlint编译时会发出两个警告。其中一个说明类型C<Double>是必需的,但找到C,即使返回类型非常清楚C<Double>

我找到了一个摆脱两种警告的解决方案,但我不理解(并且想知道)为什么这首先是一个警告以及为什么它会消失。

代码:

public class Test {
    public static void main(String[] args) {
        B b = new B();
        thing(b);
    }

    static void thing(A a) {
        C<Double> c = a.a();
    }
}

abstract class A<T> {
    C<Double> a() {
        return new C<Double>();
    }
}

class B extends A<String> {}

class C<T> {}

警告:

Test.java:7: warning: [rawtypes] found raw type: A
    static void thing(A a) {
                      ^
  missing type arguments for generic class A<T>
  where T is a type-variable:
    T extends Object declared in class A
Test.java:8: warning: [unchecked] unchecked conversion
        C<Double> c = a.a();
                         ^
  required: C<Double>
  found:    C
2 warnings

警告的解决方案:

我将static void thing(A a)更改为static void thing(A<?> a)

可是:

a.a()没有理由返回C而不是C<Double>,这是所谓的返回类型。当A的类型参数不会影响A时,我不明白为什么.a()为raw会使其所有方法的返回类型为raw。 / p>

0 个答案:

没有答案
相关问题