Sponsored Link •
|
Summary
I came across another generic puzzle and hope that someone has some insights.
Advertisement
|
Suppose you have a class with a method f():
public class HasF { public HasF f() { System.out.println("HasF::f()"); return this; } }
Here's a class that uses HasF as a bound for its generic parameter T. It stores an object of type T, and since the type parameter erases to its first bound, the methods of HasF are available:
class Manipulator4<T extends HasF> { private T obj; public Manipulator4(T x) { obj = x; } public T manipulate() { obj.f(); } }
The problem is that, in theory, covariant return types allow a return value to be the specified type or something derived from it. So it would seem that manipulate() would be able to return a HasF or something derived from it, which is exactly what T is bounded to be. So it would seem that the definition of manipulate() is OK, but the compiler gives an error: incompatible types, found : HasF, required: T. This is further confusing because T erases to HasF.
Have an opinion? Readers have already posted 17 comments about this weblog entry. Why not add yours?
If you'd like to be notified whenever Bruce Eckel adds a new entry to his weblog, subscribe to his RSS feed.
Bruce Eckel (www.BruceEckel.com) provides development assistance in Python with user interfaces in Flex. He is the author of Thinking in Java (Prentice-Hall, 1998, 2nd Edition, 2000, 3rd Edition, 2003, 4th Edition, 2005), the Hands-On Java Seminar CD ROM (available on the Web site), Thinking in C++ (PH 1995; 2nd edition 2000, Volume 2 with Chuck Allison, 2003), C++ Inside & Out (Osborne/McGraw-Hill 1993), among others. He's given hundreds of presentations throughout the world, published over 150 articles in numerous magazines, was a founding member of the ANSI/ISO C++ committee and speaks regularly at conferences. |
Sponsored Links
|