PWI Software Documentation Help

Polymorphism

Polymorphism is a fundamental concept in object-oriented programming (OOP) that allows objects of different classes to be treated as objects of a common superclass. It enables a single interface to represent different types of objects and allows methods to have different implementations based on the object's actual class. Polymorphism promotes code reusability, flexibility, and maintainability.

There are two types of polymorphism in OOP: compile-time polymorphism and runtime polymorphism

Compile-time polymorphism

Also known as static polymorphism or method overloading, this type of polymorphism occurs when multiple methods with the same name but different parameters (number, types, or order) are defined within the same class. The appropriate method is determined at compile-time based on the arguments passed to the method.

Example:

class Calculator { public int Add(int a, int b) { return a + b; } public double Add(double a, double b) { return a + b; } }

In this example, there are two Add methods with different parameter types. The correct method will be called based on the argument types.

Runtime polymorphism

Also known as dynamic polymorphism or method overriding, this type of polymorphism occurs when a subclass provides its own implementation of a method that is already defined in its superclass. The decision of which method to call is made at runtime based on the actual type of the object.

Example:

public abstract class Animal { public abstract void Speak(); } public class Dog : Animal { public override void Speak() { Console.WriteLine("Woof!"); } } public class Cat : Animal { public override void Speak() { Console.WriteLine("Meow!"); } }

In this example, both Dog and Cat classes inherit from the Animal class and provide their own implementation of the Speak method. If you have a reference to an Animal object, you can call the Speak method without knowing the object's actual type:

Animal myAnimal = new Dog(); myAnimal.Speak(); // Outputs "Woof!" myAnimal = new Cat(); myAnimal.Speak(); // Outputs "Meow!"

In this case, the appropriate Speak method is called based on the actual type of the object at runtime.

02 February 2024