0

why polymorphism is dependent on inheritance? code example?

djechlin
  • 59,258
  • 35
  • 162
  • 290
Kelly
  • 119
  • 1
  • 1
  • 4

3 Answers3

11

Polymorphism is not inherently dependent on inheritance.

Polymorphism is a rather abstract concept about giving uniformous interfaces to different kinds of values.

In common object-oriented languages like Java or C#, these interfaces are provided through class inheritance, but this is one possible implementation of polymorphism and not the concept of polymorphism in general.

Duck typing, structural typing, C++-style templates or typeclasses all provide other implementations of polymorphism.

Just see all this polymorphous codes in order to provide an interface to ducks ...

Inheritance/Interfaces (C#):

interface Duck { void quak(); }

void DoQuak(Duck d) { d.quak(); }

Dynamic Duck-typing (Python):

def DoQuak(d):
    d.quak();

Templates (Static duck-tying) (C++):

template <typename T>
void DoQuak(const T& d) { d.quak(); }

Structural types (Scala):

def DoQuak(d : { def quak() : Unit }) { d.quak() }

Type classes (Haskell):

class Quakable a where
    quak :: a -> IO ()

doQuak d = quak d
Dario
  • 48,658
  • 8
  • 97
  • 130
  • A-god-damned-MEN! I'm tired of people thinking there's something special about OOP languages that makes them the only source of polymorphism! Add Modula-3's generics (which are different from C++ templates in important ways) to the list. Or Eiffel's generics, for that matter. – JUST MY correct OPINION Mar 11 '10 at 10:12
1

Polymorphism is the ability for an object to vary behavior(behave differently) based on its type.

Overriding is the means by which you achieve polymorphism. An override function "replaces" a function inherited from the base class.

This part of SO has a discussion/examples that might interest you further.

Community
  • 1
  • 1
KMån
  • 9,896
  • 2
  • 31
  • 41
0

Providing your interfaces match you don't need to use inheritance.

It's easier to ensure interfaces match and provide a guarantee by using a contract such as subclassing a base class that has abstract methods (that you have to provide an implementation for in your subclass) or implement a shared interface.

Interfaces don't contain any code, they're just what they say on the tin - a blueprint for a certain interface. Base classes can contain some implementation but abstract classes and methods must be derived / subclassed to be used.

Then you can apply type hints to check for a common Interface or base class (Observer):

public function register(Observer observer) {

    observers.push(observer);

}

or check an Interface is implemented:

if (class instanceof MyInterface) {
    // call a method that exists in your interface
    class.myMethod();
}

or your object extends a base-class that has certain abstract methods:

if (class instanceof MyBaseClass) {
    class.guaranteedToExist();
}
Greg K
  • 10,770
  • 10
  • 45
  • 62