C# Classes Polymorphism 3


This entry is part 3 of 5 in the series C# Polymorphism

Here is an example of polymorphism using our familiar Animal and Cow classes.

using static System.Console;
namespace Polymorphism3
{   // Code written by Mike and adopted from book
    // C# A Beginner's Tutorial - Chapter 11.
    class Program
    {
        static void Main(string[] args)
        {
            Animal animal;
            animal = new Cow();
            // output of line below: Polymorphism3.Cow
            WriteLine(animal.GetType().ToString());
            // output of line below: I am a cow
            animal.Work();
            // the line above is Polymorphism in action
            Cow cow = (Cow)animal;
            // output of line below: I am Mooing
            cow.Moo();
            ReadKey();
        }
    }
    class Animal  {
        public virtual void Work()  {
            WriteLine("I am an animal");
        }
    }
    class Cow : Animal  {  // inherits from animal
        public override void Work()  {
            WriteLine("I am a cow");
        }
        public void Moo()  {
            WriteLine("I am Mooing");
        }
    }
}
Series Navigation<< C# Classes Polymorphism 2C# Method Overriding >>