1

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?"

J.J. Beam
  • 2,612
  • 2
  • 26
  • 55
  • 4
    Does it work when you use `class B extends A`? – f1sh Jan 10 '19 at 13:30
  • yep: `extends A` (@f1sh beat me too it!) – Hovercraft Full Of Eels Jan 10 '19 at 13:30
  • The use of `A` in `extends A` is a "raw type", that is, a generics type without a generics parameter. Whenever you see a raw type be aware that it is a source of trouble. In this case, the thought "`A` is a raw type" will naturally lead to "therefore add a type parameter", resulting in `B extends A` (or one of the trickier variations on that), as others have answered. – Lew Bloch Jan 10 '19 at 18:06

3 Answers3

2

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>
f1sh
  • 11,489
  • 3
  • 25
  • 51
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

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
0

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

Potato
  • 628
  • 5
  • 8