Lets say we have a baseclass called A
and some subclasses (B
,C
,D
, etc.). Most subclasses have the method do()
but the baseclass does not.
Class AA
provides a method called getObject()
, which will create an object of type B
, or C
or D
, etc., but returns the object as type A
.
How do I cast the returned object to the concrete type and call its do()
method, if this method is available?
EDIT:
I'm not allowed to change the implementation of Class A
, the subclasses or AA
, since im using a closed Source API.. And yeah, it does have some design issues, as you can see.
You can test with instanceof
and call the do()
methods:
A a = aa.getObject();
if (a instanceof B) {
B b = (B) a;
b.do();
}
// ...
I think a better idea is to actually have class A
define the do()
method either as an abstract method or as a concrete empty method. This way you won't have to do any cast.
If you are not allowed to change any of the classes than you could define a class MyA extends A
which defines the do()
method and MyB
, MyC
,... and a MyAA
that would basically do what AA
does, just that it returns objects of type MyB
, MyC
....
If this is not ok then I don't see another way than checking if the returned object is of type B
and do a cast to B
and so on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With