■ Polymorphism
• The word polymorphism means having many forms.
• Ability to create many form/Achieving multiple behaviour with same
method/object.
• polymorphism is a fundamental OOP concept that allows objects of different types to be treated as objects of a common base type.
• It allows objects to be treated as instances of their parent class rather than their actual class.
➤ Example
Consider a scenario where you have a base class Animal and several derived classes such as Dog, Cat, and Bird. Each derived class will override a method Speak to provide its specific implementation.
Every animal can speak, but each type of animal speaks in different way so each animal need to implement speak method according to their behavior, this is what polymorphism is one name many form
class Animal
{
// Virtual method in the base class
public virtual void Speak()
{
Console.WriteLine("Animal makes a sound");
}
}
class Dog : Animal
{
// Override the Speak method in the Dog class
public override void Speak()
{
Console.WriteLine("Dog barks");
}
}
class Cat : Animal
{
// Override the Speak method in the Cat class
public override void Speak()
{
Console.WriteLine("Cat meows");
}
}
class Bird : Animal
{
// Override the Speak method in the Bird class
public override void Speak()
{
Console.WriteLine("Bird chirps");
}
}
class Program
{
static void Main()
{
// Create instances of derived classes and assigning it to base class reference
Animal dog = new Dog();
Animal cat = new Cat();
Animal bird = new Bird();
// Call the Speak method on each instance
dog.Speak(); // Outputs: Dog barks
cat.Speak(); // Outputs: Cat meows
bird.Speak(); // Outputs: Bird chirps
}
}
➤ There are two main types of Polymorphism
1) Compile-Time Polymorphism (Static Polymorphism)
• It resolves method calls at compile time rather than at runtime
• static polymorphism is achieved through method overloading, operator overloading and method hiding.
2) Run-Time Polymorphism(Dynamic Polymorphism)
• It resolves method calls at run time rather than at compile time
• It allows a method to perform differently based on the object that it is acting upon.
• This is typically achieved through method overriding and interfaces.
➤ When or why we made a method a virtual method
• a method is made virtual to allow derived classes to override it and provide their specific implementations.
• This is a key aspect of achieving polymorphism.
• If you anticipate that new derived classes might need to implement or modify the behavior of certain methods.
Comments
Post a Comment