I was asked in an interview how you can achieve dynamic polymorphism without extending a class. How can this be done?
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
1.4m articles
1.4m replys
5 comments
57.0k users