Polymorphism
What is Polymorphism?
Object oriented programming supports polymorphism. This means that class variables and methods can take on many different forms which are appropriate for the specific object. There are two forms - static (not on the OCR spec) and dynamic.
Static Polymorphism - Member Methods
Member methods or any function can take on different forms depending on the number, data type and order of parameter variables passed in. The name of each parameter variable is irrelevant.
// no parameters...
public void Greet() {
Console.WriteLine("Hello there stranger!");
}
// one string parameter...
public void Greet(string name) {
Console.WriteLine("Hello there " + name);
}
// two string parameters
public void Greet(string Title, string LastName) {
Console.WriteLine("Good day " + Title + " " + Lastname);
}
// one integer parameter
public void Greet(bool IsGroup) {
Console.WriteLine(IsGroup ? "Hello all of you": "Hello my friend");
}
Dynamic Polymorphism
Polymorphism means that objects of different types can be treated in the same way. For example different types of birds make different sounds.
The code below shows three implementations of the makeSound()
method which are appropriate for the sub classes: Duck
, Crow
and Canary
.
// no parameters...
public void Greet() {
Console.WriteLine("Hello there stranger!");
}
// one string parameter...
public void Greet(string name) {
Console.WriteLine("Hello there " + name);
}
// two string parameters
public void Greet(string Title, string LastName) {
Console.WriteLine("Good day " + Title + " " + Lastname);
}
// one integer parameter
public void Greet(bool IsGroup) {
Console.WriteLine(IsGroup ? "Hello all of you": "Hello my friend");
}
Since all inherit from Bird
they can be stored in an array of the parent class i.e. Bird
.
C# Example
Here is the parent class Bird and subclasses Canary, Duck and Crow:
Here is the array. The array is created as the parent class. Each object is stored as its subclass e.g. Duck. When accessing each object cast back to the sub class.
Example: the Stack and Queue Classes
Another example using data structures could be if both the Stack and Queue class inherited from the class Data Structure. The method Add inside the queue class it would be implemented to add to the back of the queue. The method Add()
in the stack class could be implemented to add to the front of the queue. So calling the same method Add has different behaviours depending on the sub class.