0

for the following interfaces and classes I have:

public interface Animal { //cant change this

public interface AnimalGroup<T extends Animal> { //cant change this

public class DogPack<T extends Animal> implements AnimalGroup<T> { //cant change implements AnimalGroup<T>

public class Dog implements Animal { //can change this

this works:

    AnimalGroup<Animal> pack;
    pack = new DogPack<Animal>();

this does not compile due to type mismatch: cannot convert from DogPack to AnimalGroup

    AnimalGroup<Animal> pack;
    pack = new DogPack<Dog>();

Can anyone offer any guidance as to why? I can get various combinations to work but not quite sure if the above does not work because Dog does not inherit/extend Animal (it cant)

Thanks

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152
  • Generics are *invariant*. That means the types have to match exactly. Classes (with polymorphism) are *covariant*. That means a `Dog` is-a `Animal` and you can use `Dog` where an `Animal` is permitted. In this case I think you'll need to declare your `AnimalPack` as `` because that part has to match. (P.S. when you have problems like this it usually means you're trying to use generics where you should be using regular classes and polymorphism.) – markspace Mar 10 '21 at 05:27
  • (In this case I think you should be using either `AnimalPack` or you should use `AnimalPack` and `DogPack` without generics, but not trying to use both. It's redundant at least, and probably wrong design too.) – markspace Mar 10 '21 at 05:29
  • You need to use proper formatting and generally pay attention to the instructions. Your generics were getting eaten because you didn't tag them as code. – chrylis -cautiouslyoptimistic- Mar 10 '21 at 05:36

0 Answers0