What is polymorphism of subtypes in C #? How to implement it?
1 answer
Subtype polymorphism is what is commonly understood by polymorphism in object-oriented programming. It lies in the fact that the calling code uses the object, relying only on its interface (contract), without knowing the actual type. This approach allows subtypes to implement their behavior, and so on. change the behavior of the program without recompiling the client code. Take an example from Wikipedia:
public abstract class Animal { public abstract String Talk(); } public class Cat : Animal { public override String Talk() { return "Meow!"; } } public class Dog : Animal { public override String Talk() { return "Woof!"; } } public class Program { private static void Write(Animal animal) { Console.WriteLine(animal.Talk()); } public static void Main(String args[]) { Write(new Cat()); Write(new Dog()); } }
Here, the Animal
class is a base type that declares an interface (contract). The interface consists of only one method. Next we have two child classes, Cat
and Dog
, each of which overrides the Talk
method with its own behavior corresponding to this class.
The Program.Write
method is in this case a client — it takes an Animal
object as an input and calls the Talk
method. However, he does not know anything about the actual type of the object, but uses only the declared interface. Flipping him with instances of different types - Cat
and Dog
- we get different behavior (different text is output to the console).