0

In my java code, I have an instance of a generic parent data structure being instantiated with a new instance of the generic child structure.

private ParentHand<ParentCard> hand;

public Foo() {
    // Java: Incompatible types: ParentHand<ParentCard>
    // cannot be converted to ChildHand<ChildCard>();
    hand = new ChildHand<ChildCard>();
}

The parent interfaces are constructed as follows:

public interface ParentHand<T extends ParentCard> { ... }
public interface ParentCard extends Comparable<ParentCard> {...}

The child interfaces are constructed as follows:

public interface ChildHand<T extends ParentCard> implements ParentHand<T> { ... }
public interface ChildCard implements ParentCard { ... }

I believe the above should work because of polymorphism. This is written with Java 11. Why does Foo() throw this error?

StageCodes
  • 33
  • 7
  • 3
    Does this answer your question? [Why is List a subtype of List, but not of List?](https://stackoverflow.com/questions/11199791/why-is-liststring-a-subtype-of-list-but-not-of-listobject) – Henry Twist Mar 09 '21 at 03:08
  • Suppose there were class `DaughterCard`, which is also a child of `ParentCard`, but is different from `ChildCard`. You don't want to be able to write `hand.add(new DaughterCard());` as the next line of `Foo`, because `hand` references a hand of `ChildCard` objects. But if the above compiled, you'd be able to, so you'd lose the type safety of your collection. – Dawood ibn Kareem Mar 09 '21 at 03:09
  • Have a read of Jon Skeet's answer to the duplicate question that I found. Jon explains this beautifully. – Dawood ibn Kareem Mar 09 '21 at 03:12
  • Definitely reading through every link I can, I appreciate the link to Jon Skeet's answer as well. Thank you @DawoodibnKareem for your interpretation and how it relates to my specific "card" scenario, as it helps me understand the problem better. – StageCodes Mar 09 '21 at 03:20
  • No problem. Everyone takes a while to get their head around this particular point. All the best with your ongoing learning. – Dawood ibn Kareem Mar 09 '21 at 03:23
  • Why is it that I get the error despite having the type constraint in my generic? In order to add to a list of parents, the type added must implement the specific child card. `public interface ParentHand` @DawoodibnKareem – StageCodes Mar 09 '21 at 03:31
  • Writing `T extends ChildCard` precludes `T` from being `ParentCard`. – Dawood ibn Kareem Mar 09 '21 at 03:33
  • I should also mention that `ChildCard implements ParentCard`. – StageCodes Mar 09 '21 at 03:35

0 Answers0