I have a lot of classes which are basically equivalent, ie have almost the same functions in all respect. Let’s call them A and B. There are hundreds of methods that are using A and now due to code changes I have to change them to B.
Is there a way by which I can program a mapping between A and B such that I have minimal code changes?
If
Ais notfinal, you can makeB extends A, and haveB‘s methods@OverrideA‘s. Then wherever previously you were invoking methods on aninstanceof A, you now provide aninstanceof B, and let dynamic dispatch handle the rest.This is called polymorphism. It only works with non-
staticmethods having the same exact signature. You can not@Overridestaticmethods.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 implementationArrayList<E>. If you wrote an entire library that works with anArrayList<E>, doing all the usualadd/addAll/removeetc, and now you must use aLinkedList<E>instead, then you’d have little choice but to go to the source code and change all theArrayList<E>toLinkedList<E>, and hope that the change doesn’t break another code which still assumed thatArrayList<E>was used.If instead your library works with a
List<E>, then switching to aLinkedList<E>need to be done only wherever the objects are created. All the other code that was doing theadd/addAll/removewould’ve still worked just fine, since those are methods that are defined in theinterface List<E>which all implementors will have.It’s not clear from the current context, but if
AandBare so similar, then perhaps they belong to some typeX. If so, you should consider defininginterface X, and haveA implements X, andB implements X.See also
Related questions