How Do You Establish Polymorphism in C# (C Sharp)Polymorphism
is an important feature of Object Oriented Programming. Polymorphism gives
the ability to take multiple forms. In programming sense, when the same
method takes more than one form, then it is polymorphism. This article
will illustrate polymorphism with examples.
There are two different types of polymorphism namely: Static/Compile
Time Polymorphism Static/Compile Time Polymorphism: Static polymorphism is achieved using method overloading and operator overloading. Consider the following example: class sampleClass
{ Output of this code will be: Displaying
Values of obj.. In this example, you defined the same method setData thrice with different set of arguments. This is known as method overloading. You would have done this frequently in constructors. You might have defined many constructors for the class with different set of arguments. In this example, you created testClass and instantiated sampleClass inside Main method of testClass. After instantiating, you have called different forms of setData based on your need. These forms of method calls are mapped to the actual methods during compile time. Hence the name: compile time polymorphism. Ensure that the overloading methods must have the same name but the number of arguments or the type of arguments passed to each form of the method should be different. Dynamic/ Runtime Polymorphism: Dynamic polymorphism is implemented using method overriding. Consider the following example: class baseClass
{ Output of this code will be: In baseClass
In this example, baseClass contains a virtual method called displayMsg. baseClass is then inherited by two different derived classes each of them overriding displayMsg method. Inside Main method of testClass, you create an instance of type baseClass using the following statement: baseClass obj; This object obj can now reference baseClass or derived1Class or derived2Class based on the actual instantiation done using new operator. For example, baseClass obj = new derived1Class(); This statement will make the object obj reference the derived1Class. Hence calling obj.displayMsg will execute displayMsg method in derived1Class even though the object obj is of type baseClass. This binding of method call to the actual method happens at run time based on the reference made by the object. This is termed as dynamic/runtime polymorphism. Unlike method overloading, method overridden in the derived class should have the same signature as that of the base class method with the same number of arguments and same type of arguments.
|