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.
If you are not allowed change
A
but you can change the subclasses then you can make an interface with the methoddo()
and let all the subclass implement that interface.Then you don't need a cast. Otherwise you will need some explicit downcasts.
Best way to do it have
A
class that method. But since you are not allowed to change any class. I would advice you to create a wrapper instance around all classes using reflections.Static method in Below class is used just to show how to do it. You can have separate instance variable which can Wrap A in E.
Second option is
instance of
for which you will have to check for the type and then cast it.