Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to achieve dynamic polymorphism without extending a class

I was asked in an interview how you can achieve dynamic polymorphism without extending a class. How can this be done?

like image 431
Rahul Singh Avatar asked Sep 10 '12 07:09

Rahul Singh


People also ask

How will you achieve polymorphism without using base class?

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.

How do you achieve dynamic polymorphism?

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.

Can we implement polymorphism without inheritance?

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).

Can we achieve polymorphism without inheritance in C++ justify your answer?

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 ...


2 Answers

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

like image 64
yegor256 Avatar answered Sep 20 '22 22:09

yegor256


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.

like image 22
Stephen C Avatar answered Sep 20 '22 22:09

Stephen C