0

I have an Animal class and a Cat class which extends Animal (Cat is an Animal) I have defined a generic class:

public class Employee<T extends Animal> {
    T obj;
    Employee(T o){
        obj=o;
    }
    String getName(Employee<T> a){
        return "ok";
    }
}

In a test class, if i write this, it gives me the following error error:

Employee<Cat> cat = new Employee<Cat>(null);
Employee<Animal> animal = new Employee<Animal>(null);
animal.getName(cat);

But if i give pass question mark for getName method, it works , i thought Cat is an Animal (Cat class extends Animal) . Any idea why i need to pass ? instead of T ?

Parameswar
  • 1,951
  • 9
  • 34
  • 57

2 Answers2

2

If you have a method getName(Employee<T> a) then this method only accepts Employee<T>, which in the case of animal.getName(a) means that it must be an Employee<Animal> (because animal is an Employee<Animal>.

If you also want to accept subclasses of the generic type, you have to say

String getName(Employee<? extends T> a)

If you also want to accept superclasses of the generic type, you have to say

String getName(Employee<? super T> a)

If you don't actually care about the generic type of the other animal, you can say

String getName(Employee<?> a)

Which of these four cases is appropriate depends on what the method actually needs to do (and how the generic type is used by the two objects and their other methods).

Thilo
  • 257,207
  • 101
  • 511
  • 656
1

Although Cat is compatible with Animal, Employee<Cat> is not compatible with Employee<Animal>. They are completely different types. Or to put it more generally, A<T> is not compatible with A<U> even if T is compatible with U.

What's the difference between <?> and <T>?

In <T>, you have a generic type parameter T, which in this case, is Animal. Thus, the method is accepting an argument of type Employee<Animal>. As I have said, putting an Employee<Cat> in Employee<Animal> just does not work, which is why the code fails to compile.

<?> on the other hand, allows anything to be put into the brackets, whether it is Cat, Dog, Tiger, Unicorn, whatever.

P.S. Why does Employee have a field of type Animal? That's kind of weird... just saying...

Sweeper
  • 213,210
  • 22
  • 193
  • 313