Java downcasting and is-A has-A relationship

Posted by msharma on Stack Overflow See other posts from Stack Overflow or by msharma
Published on 2010-05-13T19:12:50Z Indexed on 2010/05/13 19:34 UTC
Read the original article Hit count: 280

Filed under:
|

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.

© Stack Overflow or respective owner

Related posts about downcasting

Related posts about java