I was asked in an interview how you can achieve dynamic polymorphism without extending a class. How can this be done?
Polymorphism through inheritance:
Polymorphism through encapsulation (Decorator pattern):
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
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.
According to my experience, in most job interviews the questions do not look for way too elaborate answers, and most of the times are just tricky questions, so if they asked specifically for polymorphism without extending a class, then I would say:
Yes, you can have dynamic polymorphism by implementing an interface rather than extending a class
then if they would ask for more options then it would be ok to bring up proxies, patterns or something else.
Hope it helps!