Basics object-oriented programming with C#: Polymorphism
Welcome to the wild and wonderful world of polymorphism, my fellow programmers! Polymorphism is one of the fundamental concepts of object-oriented programming (OOP) and it allows us to use a single interface to represent multiple types of objects. It’s like magic, but with less wand waving and more code typing.
In C#, polymorphism is achieved through the use of virtual
and override
keywords, abstract
classes, and interface
.
Let’s start with the virtual
override
keywords. The virtual
keyword is used to indicate that a method or property can be overridden in a derived class. For example, let's say we have a base class called "Animal" with a virtual method called "Speak()".
public class Animals
{
public virtual void Speak()
{
Console.WriteLine("Animal can't speak.");
}
}
Let’s say we have a derived class called “Dogs” that inherits from the “Animals” class. We can override the “Speak()” method in the “Dogs” class to make the dogs bark.
class Dogs : Animals
{
public override void Speak()
{
Console.WriteLine("Woof woof");
}
}
Now, if we create an instance of the “Dogs” class and call the “Speak()” method, it will print “Woof woof” instead of “Animals can’t speak.”