I was asked in an interview how you can achieve dynamic polymorphism without extending a class. How can this be done?
Implementing Interfaces is Inheritance. you can achieve polymorphism without inheritance using composition. Composition is an oop topic, when we create an object of a class in an other class we called it composition.
We can achieve dynamic polymorphism by using the method overriding. In this process, an overridden method is called through a reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable.
Real polymorphism in General can not be acheived without inheritance. Languages that are not object-oriented provide forms of polymorphism which do not rely on inheritance (i.e parametric polymorphism).
I agree the answer is yes, in polymorphism, you derive from a base class then override the the implementation in the derived class (polymorphism) so that you the derived class can specify a more specialized or different implementation by implementing the base class and usually methods that override the base class have ...
Decorator design pattern that exploits encapsulation is what you're looking for.
Polymorphism through inheritance:
class Cat { void meow() { // meow... } } class Lion extends Cat { }
Polymorphism through encapsulation (Decorator pattern):
interface Cat { void meow(); } class Lion implements Cat { private Cat cat; void meow() { this.cat.meow(); } }
ps. More about decorators: http://www.yegor256.com/2015/02/26/composable-decorators.html
The simple solution is to write a class that implements an interface rather than extending a base class.
Another solution is to create a dynamic proxy ... which is essentially a clever way of implementing an interface without explicitly writing the class. See the Proxy
javadoc for details.
And yes, these are (or can be) examples of the decorator pattern, though the key thing here is the implementation techniques rather than the design pattern.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With