| Author |
Returning generic lists that implement a common interface
|
Jussi Taimiaho
Ranch Hand
Joined: Mar 01, 2004
Posts: 40
|
|
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
Joined: Jul 11, 2001
Posts: 14112
|
|
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).
|
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
|
 |
 |
|
|
subject: Returning generic lists that implement a common interface
|
|
|