I hear that in Java I can achieve polymorphism through injection at runtime. Can someone please show a simple example of how that is done? I search online but I can't find anything: maybe I am searching wrong. So I know about polymorphism through interface and and extension such as
class MyClass extends Parent implements Naming
in such case I am achieving polymorphism twice: MyClass is at once of type Parent and Naming. But I don't get how injection works. The idea is that I would not be using the @Override keyword during injection. I hope the question is clear. Thanks.
So the end result here, per my understanding, is to change the behavior of a method through injection instead of by @Override it during development.
This is known as inhertiance and not polymorphism.
MyClassis aParentandMyClassis also aNaming. That being said,inheritanceallows you to achivepolymorphism.Consider a class other than
MyClassthat also implementsNaming:Now consider a method that takes a
Namingargument somewhere in your code base :The
doSomethingmethod can be passed an instance of anyclassthat implementsNaming. So both the following calls are valid :Observe how you can call
doSomethingwith different parameters. At runtime, the first call will callsomeMethodDefinedInTheInterfacefromMyClassand the second call will callsomeMethodDefinedInTheInterfacefromSomeOtherClass. This is known asruntime-polymorphismwhich can be achieved through inheritance.That's true in the broader sense. To
injectsomething into a class, the class should ideally favorcompositionoverinheritance. See this answer that does a good job in explaining the reason for favoring composition over inheritance.To extend the above example from my answer, let's modify the
doSomethingmethod as follows :Observe how
ClassHasANamingnow has-aNamingdependency that can be injected from the outside world :If you use the Factory pattern, you can actually chose which subclass gets instantiated at runtime.
Do you think we could have done what we did above using
inheritance?The answer is No.
ClassIsANamingis bound to a single implementation of thesomeMethodDefinedInTheInterfacemethod at compile time itself. `