If A
is not final
, you can make B extends A
, and have B
's methods @Override
A
's. Then wherever previously you were invoking methods on an instanceof A
, you now provide an instanceof B
, and let dynamic dispatch handle the rest.
This is called polymorphism. It only works with non-static
methods having the same exact signature. You can not @Override
static
methods.
See also
Related questions
On interfaces
Depending on why you were doing this, you should know learn the concept of interfaces and how they're used in object-oriented programming to allow precisely this kinds of flexibility and convenience.
Consider the interface List<E>
, for example, and an implementation ArrayList<E>
. If you wrote an entire library that works with an ArrayList<E>
, doing all the usual add/addAll/remove
etc, and now you must use a LinkedList<E>
instead, then you'd have little choice but to go to the source code and change all the ArrayList<E>
to LinkedList<E>
, and hope that the change doesn't break another code which still assumed that ArrayList<E>
was used.
If instead your library works with a List<E>
, then switching to a LinkedList<E>
need to be done only wherever the objects are created. All the other code that was doing the add/addAll/remove
would've still worked just fine, since those are methods that are defined in the interface List<E>
which all implementors will have.
It's not clear from the current context, but if A
and B
are so similar, then perhaps they belong to some type X
. If so, you should consider defining interface X
, and have A implements X
, and B implements X
.
See also
Related questions