Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Returning generic lists that implement a common interface

 
Jussi Taimiaho
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have slight problem with class-logic and generics. I have a structure where there is interfaces and implementations (MyType, MyTypeImpl).

What I have is:


Interface Point introduces:


In practice my PointImpl contains LineImpl �objects, while AnotherPointImpl contains AnotherLineImpl �objects. However, using generics, I cannot return directly:

Because the type is wrong: List<LineImpl> is not List<Line> .

While to my logic this should be correct way to work. Because if I have:


MusicShop introduces:


MyMusicShop has


All ideas on this topic appreciated,
jussi

[escaped less-than and greater-than characters for clarity --Frank Carver]
[ January 17, 2007: Message edited by: Frank Carver ]
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Although LineImpl is a subtype of Line, List<LineImpl> is *not* a subtype of List<Line>. The reason is that cannot add a Line to List<LineImpl>, so not everything you can do with a List<Line> you can also do with a List<LineImpl>.

A solution is to use a List<? extends Line> as the return type. That way you can also return a List<LineImpl>, but you cannot call methods that get a Line as parameter on that List (which in consequence basically makes it a read-only List).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic