why polymorphism is dependent on inheritance? code example?
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
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();
}
精彩评论