Polymorphism by definition means many forms. Which signifies, an object can exist in different forms.
Story :
abstract class Animal : LivingBeing { public void breathe() { System.Console.WriteLine("Breathes Oxygen."); } public abstract void sound(); //Undefined so abstract }
Story :
public class Cat : Animal { public override void sound() { System.Console.WriteLine("Cats Meao"); } public void catRelated() { System.Console.WriteLine("It loves sleeping."); } }
And for Dog :
public class Dog : Animal { public override void sound() { System.Console.WriteLine("Dog Barks"); } public void dogRelated() { System.Console.WriteLine("Very obidient."); } }
Thus, we have the below hierarchy :
So we have seen how Animal exists in various forms. Since Animal is abstract, we cannot create any object out of it. Also if you think in reality Animal does not exist. But Cat, Dog etc exists and thus we can create Cat or Dog objects.
Now, comes the most vital part. Creating Cat and Dog objects using the Animal reference. Also known as Dynamic Binding. Little tricky but used everywhere.
abstract class Animal { public void breathe() { System.Console.WriteLine("Breathes Oxygen."); } public abstract void sound(); //Undefined so abstract } class Cat : Animal { public override void sound() { System.Console.WriteLine("Cats Meao"); } public void catRelated() { System.Console.WriteLine("It loves sleeping."); } } class Dog : Animal { public override void sound() { System.Console.WriteLine("Dog Barks"); } public void dogRelated() { System.Console.WriteLine("Very obidient."); } } class CreateLivingBeing { public static void Main(string[] args) { Animal animalCat = new Cat(); Animal animalDog = new Dog(); animalCat.sound(); // Calls the sound() behaviour of Cat. animalDog.sound(); // Calls the sound() behaviour of Dog. animalCat.breathe(); // Calls the breathe() behaviour of Animal. animalDog.breathe(); // Calls the breathe() behaviour of Animal. } }
In the above code, we have seen something new. The Animal reference variable animalCat is holding a Cat object.
Animal animalCat = new Cat(); Animal animalDog = new Dog();
Story :
Now, lets dig the below line:
Animal animalCat = new Cat();
Here Animal is the Refrence Type, animalCat is the refrence variable and new Cat() is the Instance/object.