Thursday, March 20, 2014

Polymorphism vs Overriding vs Overloading

Summarize the relationship between polymorphism with overriding and overloading.

Polymorphism is the ability of a class instance to behave as if it were an instance of another class in its inheritance tree, most often one of its ancestor classes. For example, in Java all classes inherit from Object. Therefore, you can create a variable of type Object and assign to it an instance of any class. It always involves class inheritance and method overriding.

An override is a type of function which occurs in a class which inherits from another class. An override function "replaces" a function inherited from the base class, but does so in such a way that it is called even when an instance of its class is pretending to be a different type through polymorphism. Referring to the previous example, you could define your own class and override the toString() function. Because this function is inherited from Object, it will still be available if you copy an instance of this class into an Object-type variable. Normally, if you call toString() on your class while it is pretending to be an Object, the version of toString which will actually fire is the one defined on Object itself. However, because the function is an override, the definition of toString() from your class is used even when the class instance's true type is hidden behind polymorphism.

Overloading is the action of defining multiple methods with the same name, but with different parameters. It can be regarded as one way of static polymorphism. Template is another way.  Static polymorphism is at compile time. Static polymorphism is in fact involves binding of functions based on number or type of arguments and is also known as parametric polymorphism.

No comments:

Post a Comment