I have an object2 that inherits from object1 and a method that populates an object1 and returns it. Since object2 is a child class of object1 can I not catch the object being returned from the method to an object2?
Object2 obj = (Object2) method();
With this I get "Object1 incompatible with Object2"
Why do not casting work. This is a child object with the same values as the parent object only with some extras.
The method populates the values that are common for all the child objects. I do this in order to simplify the code. No point of setting the common values in each childs objects own populator method when it can be done in a common populator method. [ February 14, 2008: Message edited by: Sverre Moe ]
It won't work because the object you are casting is not an "Object2."
Please don't use that sort of name for your classes. Please say "superclass" and "subclass," not "parent" or "child."
If the object you are returning is an "Object1" you can cast it to Object1 or java.lang.Object, although both would be a waste of space. You cannot cast it to an Object2.
If your Object2 has an additional method which is not in Object1, then casting would allow you to use that method. If your object is in fact an Object1, then that method will not exist. So the application would crash. Better to have a ClassCastException, however. Class casts are risky at the best of times.
What you say about "No point" is quite correct. You should be using polymorphism, then there is no need for a class cast.
posted 12 years ago
Originally posted by Campbell Ritchie:
What you say about "No point" is quite correct. You should be using polymorphism, then there is no need for a class cast.[/QB]
posted 12 years ago
You should have all the requisite methods (abstract or implemented) in the Object1 class, then they can be overridden in the Object2 class. That is implied by the Object1 return type in the method you quote. Then you can call them on all the Object2 objects without needing to know which class they are instances of. Do a Google search for "Java inheritance polymorphism." This is one of the pages you will find.
He's giving us the slip! Quick! Grab this tiny ad!