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.
MyClass
is aParent
andMyClass
is also aNaming
. That being said,inheritance
allows you to achivepolymorphism
.Consider a class other than
MyClass
that also implementsNaming
:Now consider a method that takes a
Naming
argument somewhere in your code base :The
doSomething
method can be passed an instance of anyclass
that implementsNaming
. So both the following calls are valid :Observe how you can call
doSomething
with different parameters. At runtime, the first call will callsomeMethodDefinedInTheInterface
fromMyClass
and the second call will callsomeMethodDefinedInTheInterface
fromSomeOtherClass
. This is known asruntime-polymorphism
which can be achieved through inheritance.That's true in the broader sense. To
inject
something into a class, the class should ideally favorcomposition
overinheritance
. 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
doSomething
method as follows :Observe how
ClassHasANaming
now has-aNaming
dependency 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.
ClassIsANaming
is bound to a single implementation of thesomeMethodDefinedInTheInterface
method at compile time itself. `