Updated: 1/6/2003; 4:54:52 PM.
Brian Maso's Tecno-Geek Weblog
The musings of a mild-mannered tecno-geek.
        

Tuesday, December 24, 2002

In ongoing discussions on DM's ADVANCED-JAVA list I am arguing that templetized collection classes should follow the class hierarchy of the object types being collected. For example, Stack<Dog> should extend Stack<Animal>. And of course eventually all stack clases should descend from Stack<Object> (== Stack). This allows me to cast a Stack<Dog> to a Stack<Animal>, or to a generic Stack.

My reasoning is based on Java's definition of array classes. In Java, Dog[] is a class, and it does extend Animal[]. And of course all array classes descend from Object[]. So I can cast a Dog[] to an Animal[], or to a generic Object[].

It seems that (singly-)parameterized collection classes should all follow this generic rule: COLLECTION<X> extends COLLECTION<superclass(X)>. My reasoning proceeds thus: any method in COLLECTION<X> which extracts an object reference from the COLLECTION<X> object should also have a counterpart in COLLECTION<superclass(X)>, which returns a superclass(X)-type reference. Both invocations may return references to the exact same object, since an X is a superclass(X). So I should be able to use a COLLECTION<X> wherever a COLLECTION<superclass(X)> is required, which means COLLECTION<X> extends COLLECTION<superclass(X)>.

Here's what I just realized: in Java even references follow this rule. A reference to a Dog can be cast to a reference to an Animal. Conceptually we can think of an object reference as a templatized class:

public class Reference<X> extends Reference<superclass(X)>
{
public X get();
}

(Note that I'm ignoring the illegality implied in the class definition above. You can't have a class with multiple overloaded methods whose signature differs only in return type. Above, Reference<X> has at least two overloaded versions of get(): "X get()" and "superclass(X) get()" -- the later inherited from Reference<superclass(X)>. That's a syntactic problem, not a problem with the concept I'm laying out here.)

So basically what I'm saying is that references are really just the simplest type of object collections. A cast operation is not performed on the target of the reference, but on the reference instance itself. I am casting a reference of one type in to another, and the cast operation is valid because the reference class hierarchy (which mirrors the class hierarchy of the target object's class) allows it. So, in a way, objects aren't plymorphic, object references are.


10:41:44 AM    comment []

© Copyright 2003 Brian Maso.
 
December 2002
Sun Mon Tue Wed Thu Fri Sat
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31        
Nov   Jan


Click here to visit the Radio UserLand website.

Subscribe to "Brian Maso's Tecno-Geek Weblog" in Radio UserLand.

Click to see the XML version of this web page.

Click here to send an email to the editor of this weblog.