why polymorphism is dependent on inheritance? code example?
-
1Do you know what is inheritance? – Anonymous Mar 11 '10 at 07:47
-
Reading your question title I assume you want to know 'How Polymorphism is related to Inheritance?'. – KMån Mar 11 '10 at 09:59
3 Answers
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 ...
interface Duck { void quak(); }
void DoQuak(Duck d) { d.quak(); }
def DoQuak(d):
d.quak();
Templates (Static duck-tying) (C++):
template <typename T>
void DoQuak(const T& d) { d.quak(); }
def DoQuak(d : { def quak() : Unit }) { d.quak() }
class Quakable a where
quak :: a -> IO ()
doQuak d = quak d

- 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
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.
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();
}

- 10,770
- 10
- 45
- 62