Abstract method vs Virtual method

I was confused about the difference between abstract method and virtual method. They both provide the ability for derived class to override the base class’ behavior. They both could be used for achieving OOP’s greatest polymorphic characteristics.

The biggest difference is that you can’t provide implementation for abstract method. The derived classes must provide implementation for the abstract method. In the other hand, virtual method just provide the overriding option for the derived classes. The derived classes can choose either inherit the original behavior from base class or implement their own behavior. Below are two code examples for abstract method and virtual method.

Abstract method:

namespace AbstractMethodExample
{
    class Program
    {
        static void Main(string[] args)
        {
            new Dog().MakeSomeNoise();
        }
    }

    abstract class Animal   // Abstract class
    {
        public abstract void MakeSomeNoise();   // Abstract method
    }

    class Dog : Animal
    {
        public override void MakeSomeNoise()
        {
            Console.WriteLine("Bark!");
        }
    }
}

// Output:
// Bark!

Virtual method:

namespace VirtualMethodExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Dog[] dogs = new Dog[] { new Dog(),
                                     new Puppy() };
            foreach (var dog in dogs)
            {
                dog.Bark();
            }
        }
    }

    public class Dog
    {
        public virtual void Bark()
        {
            Console.WriteLine("Rowlf!");
        }
    }

    public class Puppy : Dog
    {
        public override void Bark()
        {
            Console.WriteLine("Yip!");
        }
    }
}

// Output:
// Rowlf!
// Yip!
About

I am a professional software engineer with special interest with Java and Android development

Tagged with: ,
Posted in Programming

Leave a comment