简体   繁体   English

Java Generics - 为什么返回超级 class 实例会产生编译错误

[英]Java Generics - Why returning super class instance gives compile error

Hi the following code gives compile error but I do not understand why.您好,以下代码给出了编译错误,但我不明白为什么。

class SomeClass <T extends BaseClass> {
    T method(T x) {
        return x;                   // OK
    }
    
    T method() {
        return new BaseClass();    // compile error
    }
}

The error says requires T but provided BaseClass .错误说需要T但提供了BaseClass
And similarly this one:同样是这个:

class SomeClass {
    <T extends BaseClass> T method(T x) {
        return x;                          // OK
    }
    
    <T extends BaseClass> T method() {
        return new BaseClass();           // compile error
    }
}

I know that it can be resolved like this:我知道可以这样解决:

class SomeClass <T extends BaseClass> {
    T method(T x) {
        return x;                       // OK
    }
    
    @SuppressWarnings( "unchecked" )
    T method() {
        return (T) new BaseClass();    // OK
    }
}

But may I have some explanation on why this is not allow?但是我可以解释一下为什么不允许这样做吗?

That's just how inheritance works.这就是 inheritance 的工作原理。 Say you have a superclass A, and it has subclasses B and C. Now imagine your method accepts a parameter of type A and returns an object of type B. Your method would accept objects of type C as a parameter, but you couldn't return them because they are not of type B, even though both B and C are subclasses of A.假设你有一个超类 A,它有子类 B 和 C。现在假设你的方法接受类型 A 的参数并返回类型 B 的 object。你的方法将接受类型为 C 的对象作为参数,但你不能返回它们因为它们不是类型 B,即使 B 和 C 都是 A 的子类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM