This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes upcasting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "upcasting" Watch "upcasting" New topic
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
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: upcasting
     
    Similar Threads
    Calling overloaded constructor from another constructor - compile error
    Object and String
    Generics - Doubt in using "extends" and "super"
    instanceOf??
    Reference variable casting