| Author |
upcasting
|
Siva kandasamy
Ranch Hand
Joined: Dec 31, 2002
Posts: 139
|
|
Hi there, See the code below. "t" is an Table object. Even after upcasting to plant ie. "s = (Plant) t;", "s.carve();" still uses method defined in the class Table. How can I force, object t to use method defined in the class Plant. thanks siva
|
 |
John Smith
Ranch Hand
Joined: Oct 08, 2001
Posts: 2937
|
|
How can I force, object t to use method defined in the class Plant. The mechanism to invoke a method which is defined in the parent class and is overriden in the subclass is to refer to the super class implementation using the keyword super, as in super.carve(). However, what you are trying to do is to refer to the superclass of the superclass (i.e., two levels up), and there is no way in Java to make that reach. If you think about it, you are trying to do something anti-polymorphic, and perhaps that's why the Java language designers denied you that possibility. You have several alternatives, though: Simplify your inheritance hierarchy, so that the subclass can refer to the implementation in question using the super mechanism Define a static method in the superclass. Then any sublcasses (any number of the levels down) can call it. Rethink your design. If the overriden method can't do its job without referring to the superclass 2 levels above, perhaps the method doesn't belong to the superclass, or perhaps the subclass doesn't not really have a "IS A" relationship to the superclass. For example, the relationships that you set in your code ("Plant extends Seed" and "Table extends Tree") are very questionable. In my world, a plant is not a seed, and a table is certainly not a tree.
|
 |
Siva kandasamy
Ranch Hand
Joined: Dec 31, 2002
Posts: 139
|
|
Thanks Kononov. It makes sense. -siva
|
 |
 |
|
|
subject: upcasting
|
|
|