Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast to concrete class and call method in Java

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.

like image 926
lukuluku Avatar asked Oct 01 '12 16:10

lukuluku


2 Answers

You can test with instanceof and call the do() methods:

A a = aa.getObject();
if (a instanceof B) {
   B b = (B) a;
   b.do();
}
// ...
like image 192
Andreas Dolk Avatar answered Nov 20 '22 23:11

Andreas Dolk


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.

like image 3
Dan D. Avatar answered Nov 20 '22 22:11

Dan D.