You cannot do that. You will certainly end up with nothing more than a ClassCastException
.
If your method is a non-final method of base
(possibly overridden in subclasses) then you can cast both to a base
and call it that way.
You can also make proper use of interfaces to represent common functionality instead.
The only means of dynamic binding that Java offers is via reflection (tutorial, also java.lang.Class
documentation), e.g.:
myObject.getClass().getDeclaredMethod("display").invoke(myObject);
Bear in mind that you lose all benefits of compile-time type checking when using reflection (and also the interface is much more cumbersome) -- there is almost always a better way to accomplish the task without it (in your case, I have a hunch that there is most definitely a better way).