Friday, 19 June 2015

Polymorphism: Inheritence, Overriding and Overloading

When a class inherits/derives from a parent class it inherits all protected and public methods in the base class.

Hiding methods and Overriding


If I implement a method in the child class with the same signature as one in the base class it will hide the base class's implementation.   The compiler alerts me to this and suggests a fix of adding the new keyword.  That will work as expected in some but not all conditions.

It is perfectly legal to declare a new variable of the base class and populate it with a new child class:

Base newbie = new child();

This is because the child class has an "Is A" relationship with the base class.  A child is a base so the above works.  However if you invoke the method that has been hidden in the child class, what executes and is output is the implementation in the base class (because newbie is of type Base).  This isn't what was expected because newbie is really a child.   We want, instead of hiding the child's implementation to override the base implementation with the child implementation.

To override instead of hide a method, in the base class mark the method as virtual (which indicates we expect it to be overriden in a child class) and in the child class replace new with override in the signature of the method.

This allows the methods to implement polymorphism as the method behaves differently/correctly depending on the type of each object.
Overloading = virtual methods in a derived class.

Method Overloading

It's important to remember that the signature of a method is its name and parameter list (but not its return type).
You can overload methods - methods in a class can have the same name provided:
Different number of parameters
Different type of parameters

Overloading = same method name in one class.
You can both overload and override methods

You can also overload constructors - very handy and saves duplicating code




No comments:

Post a Comment