[otj-users] Binding inheritance and covariance
Stephan Herrmann
stephan at cs.tu-berlin.de
Tue Oct 2 00:36:43 CEST 2007
Hi,
> Will the compiler make sure that
> the callin-method will /really/ return the result of the base-call
Yes! Either the base-call result ;-)
OR null :(
But no other value is possible.
> and not something else that would be fine according to "normal" generics rules?
> E.g. from looking at
>
> [callin] <E extends List> E getList() {
>
> }
>
> it would appear perfectly fine to return any subclass/implementation of List.
appearances can be deceiving ;-)
Think of who is defining the actual replacement for E: it's the caller.
Any invocation may choose a different E like in
LinkedList l = getList(); // legal: E == LinkedList
ArrayList l = getList(); // legal: E == ArrayList
just not:
String s = getList(); // illegal: can't find an E that extends List AND is conform to String
In the first, legal variant getList() must return a LinkedList!
The contract of this method is:
"I'll return a value,
the type of which you're free to CHOOSE from all subtypes of List
AFTER I've implemented the method."
Not very useful in normal settings, ;-)
but for replace callins it looks neat, doesn't it?
(Type theory would say
"List is an upper bound for E but the exact E is unknown within getList()")
cheers,
Stephan
PS: I just tried to cheat the java compiler:
<E extends List> E getList() {
return (E)(new ArrayList());
// telling the compiler: please insert a cast,
// I'll tell you at runtime which type to cast to!
}
The compiler reported no(!) error but answered:
"Note: Test.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details."
(The byte code did of course NOT contain a cast)
Hhhmmm ;-)
More information about the otj-users
mailing list