What are the restrictions on generics at inheritance hierarchy?

问题: Suppose there is classes/interfaces hierarchy: class A<T>{ T method(T t){ return t; } } class B<T> extends A{ T method(T t){ // method(T)'...

问题:

Suppose there is classes/interfaces hierarchy:

class A<T>{
    T method(T t){
        return t;
    }
}
class B<T> extends A{
    T method(T t){ // method(T)' in 'B' clashes with 'method(T)' in 'A'; both methods have same erasure, yet neither overrides the other
        return t;
    }
}

As we see there are a compiler error. I've never came across the rules how to treat generics when inherit. What are the restrictions? (please don't be confused with inheritance IN generic type itself, i'm asking about inheritance in original classes

also don't be confused with "What is a raw type", I know the raw types, at this question I wanna figure out what are the rules for inheritance)

also don't be confused thinking I wanna fix this error. Of course class B extends A fix it. My question is about: "where can I read the restrictions?"


回答1:

You will have to use T in your class definition, so that the T wildcard gets bound to the same generic type in both A and B, resolving the conflict:

class B<T> extends A<T>

回答2:

You didn't prolong A's T, you just introduced a new type parameter T for B. Those Ts are different unless you write B<T> extends A<T>:

class B<T> extends A<T> {
    @Override
    T method(T t) {
        return t;
    }
}

Both A's T and B's T would be erased to Object, the class B would contain 2 methods Object method(Object t).

Example 8.4.8.3-4. Erasure Affects Overriding

A class cannot have two member methods with the same name and type erasure:

class C<T> {
    T id (T x) {...}
} 

class D extends C<String> {
    Object id(Object x) {...}
}

https://docs.oracle.com/javase/specs/jls/se11/html/jls-8.html#d5e14416

To read: 8.4.8.3. Requirements in Overriding and Hiding


回答3:

You compile error is just as @f1sh says.

Now as to the rules, They will have the same rules be applied to them. This would include:

Type eraser Upper, lower, and Unbounded types

Also, generics can be applied to individual methods. How and when you use them depends on what you are trying to do.

For more information https://www.tutorialspoint.com/java/java_generics.htm

  • 发表于 2019-01-12 02:26
  • 阅读 ( 259 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除