File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes OO, Patterns, UML and Refactoring and the fly likes Returning generic lists that implement a common interface Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Engineering » OO, Patterns, UML and Refactoring
Bookmark "Returning generic lists that implement a common interface" Watch "Returning generic lists that implement a common interface" New topic
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
 
Similar Threads
Generics
Generics
Generics
Generics
Generics