dynamic down-casting in Java
Oct. 12th, 2006 05:15 amI just ran into problems because of Java's static (non pun intended) typing. Say we have 3 classes:
We have an object named
When
* inside
* inside
* inside
This is indeed what happens if the
If they are static, however, Java will insist on calling the
Therefore, we need to down-cast. For example:
But this is bad, since it would require me to create a case for each and every subclass of
The code I really want is something like:
A extends B extends CWe have an object named
instance whose class is A.When
instance.inputMatcher(x,y) gets called, we would expect the Java dispatcher to look for the implementation of inputMatcher in this order:* inside
A* inside
B* inside
CThis is indeed what happens if the
inputMatcher methods are non-static.If they are static, however, Java will insist on calling the
inputMatcher() from C, because that is the declared type of instance.Therefore, we need to down-cast. For example:
if (matcherInstance.getClass().equals("A"))
result = ((A) instance).inputMatcher(x,y);
But this is bad, since it would require me to create a case for each and every subclass of
C, in which I down-cast instance to that type.The code I really want is something like:
result = downcast(instance, instance.getClass()).inputMatcher(a,b);
(no subject)
Date: 2006-10-12 05:41 am (UTC)(no subject)
Date: 2006-10-12 12:54 pm (UTC)(no subject)
Date: 2006-10-12 06:32 pm (UTC)The keyword "static" is highly misleading as what it does to a method has nothing whatsoever to do with what any programmer or normal person has as their definitions of "static".
(no subject)
Date: 2006-10-12 05:42 am (UTC)(no subject)
Date: 2006-10-12 05:56 am (UTC)Static means two things: (1) doesn't pass the 'this' pointer in, so you have no access to the instance's guts; (2) doesn't do dynamic dispatch.
Those two are separable concepts -- (1) means you save pushing an unused argument on the stack, so performance hogs go for it (which could conceivably matter in a recursive function). You could still do dynamic dispatch to figure out what function to call first.
(no subject)
Date: 2006-10-12 06:01 am (UTC)This is "convenient" in terrible ways, like unityped languages.
(no subject)
Date: 2006-10-12 05:40 pm (UTC)(I mean, Java is of course evil, but that's another fight I don't want to get in to today.)