HI,
I have a down casting question, I am a bit rusty in this area.
I have 2 clasess like this:
class A{ int i; String j ; //Getters and setters}
class B extends A{ String k; //getter and setter}
I have a method like this, in a Utility helper class:
public static A converts(C c){}
Where C are objects that are retireved from the database and then converted.
The problem is I want to call the above method by passing in a ‘C’ and getting back B.
So I tried this:
B bClasss = (B) Utility.converts(c);
So even though the above method returns A I tried to downcast it to B, but I get a runtime ClassCastException.
Is there really no way around this? DO I have to write a separate converts() method which returns a B class type?
If I declare my class B like:
class B { String k; A a;} // So instead of extending A it has-a A, getter and setters also
then I can call my existing method like this:
b.setA(Utility.converts(c) );
This way I can reuse the existing method, even though the extends relationship makes more sense. What should I do? Any help much appreciated. Thanks.
The cast from type
Ato typeB:doesn’t work because objects of type
Adon’t have all the methods that might be called from references of typeB. What would you expect to happen if you calledon the next line? The underlying object has no member variable
k, so this cast is not allowed.You can use references of the higher types in your class hierarchy to refer to objects of lower types, but not the other way around.
Without knowing more, I think the best thing to do is implement multiple methods
If
BextendsA, then you should still benefit from some code reuse in the constructors of your classes.