What is polymorphism ?
Polymorphism – code reuse mechanism. You’re creating a class library. You create a class diagram in Visual Studio and add the classes and methods you think you are going to need. You notice several of your classes have methods which more or less do the same thing, how they do it being different of course. You group these classes together by applying a common interface. Now you’re able to create a class which can work with any type as long as it’s part of the group – this is polymorphism.
Example
You are creating a class library to process trade objects – equity trades, bond trades etc. You come up with the following initial design:
It’s clear that the EquityTrade, BondTrade and OptionTrade classes share a common interface. Here is an opportunity for code-reuse via polymorphism. You modify your original design to come with this:
Now you have an abstract base class and 3 descendants – EquityTrade, BondTrade and OptionTrade. You’ve created your object group which shares a common interface. Next, you modify your TradeLogger class to take advantage of this common interface. Instead of requiring 3 different methods to log trades, you now just need a single method – LogTrades, whcih accepts a collection of the base type – TradeBase. Here are the code listings in full and some sample output:
Notes
1. Instead of requiring 3 different methods in TradeLogger to log each type of trade, now you only need 1 – LogTrades
2. You can now add additional trade type classes without needing to change the TradeLogger.LogTrades method – code reuse
3. Base class has the ability to reach into descendant classes via the intrinsic “this” parameter
4. Coding everything in terms of the base class guarantees that your methods will work with all descendants
5. Avoid declaring variables of a particular concrete type – commit only to the public interface defined by an abstract type or interface implementation.
Rules
Non virtual method resolution is determined by the variable type at compile time. e.g. a base class declares the function ‘public double GetPrice()’. A descendant class also also declares the method ‘public double GetPrice()’.
BaseClass myBaseClass = new DescendantClass()
double Px = myBaseClass.GetPrice(); -> the compiler will execute BaseClass.GetPrice()
At compile time, the variable type is BaseClass, so the compiler will call BaseClass.GetPrice();
Virtual method resolution is determined at runtime by the instance type. e.g.
TradeBase et = new EquityTrade();
foreach (TradeBase t in Trades)
{
t.LogTrade();
}
LogTrade is a virtuaal method. At runtime, the instance type is EquityTrade, therfore the compiler will execute EquityTrade.LogTrade()




Leave a comment