Difference between Abstract and virtual – Good to know series

Though the concept is really simple but there is always an edge confusion between the two. Lets discuss them one by one using example. To understand the concept of Abstract lets consider one of this easy case domain problem. Lets discuss the characteristics of an animal. An animal can have 4 legs if its a horse and two legs if its a Kangaroo (ok you can argue that the arms are legs as well but lets assume that its only two legs and two arms). When i define a object of such characteristics i cant really say directly that an animal has 4 legs. I mean in real life it could have 4 but not when its a Kangaroo. Let me define the two processes separately

If we have a domain case where we say that we cannot haven’t an object of Animal class because we don’t know if it would have 4 or 6 legs. but we could have Horse or Kangaroo objects. Then we define the animal class abstract. What it will do it one it could restrict the type animal to be instantiated and secondly it would force all the child classes to implement the base class abstract method.

If we have a domain case where we have a Passenger class which could travel with ticket. But if its European passenger then we need to check the passport only and if its Non European passenger then we need to check the Passport and visa. To implement that check the example below where the base class(Passenger) method is overridden by the child class based on their nature

 

 

class Program
	{
		static void Main(string[] args)
		{
			Console.WriteLine("Abstract");
			var lion = new Lion();
			Console.WriteLine("Lion has " + lion.Legs() + " legs");
			var kangaroo =new  Kangaroo();
			Console.WriteLine("Kangroo has " + kangaroo.Legs() + " legs");
 
			Console.WriteLine("Virtual");
			var europian = new Europian();
			Console.WriteLine("If europian then " );
			europian.CheckPoint();
			var nonEuropian = new NonEuropian();
			Console.WriteLine("If non europian then ");
			nonEuropian.CheckPoint();
 
			Console.ReadLine();
		}
	}
 
	public abstract class Animal
	{
		public abstract int Legs();
	}
 
	public class Lion : Animal
	{
		public override int Legs()
		{
			return 4;
		}
	}
 
	public class Kangaroo : Animal
	{
		public override int Legs()
		{
			return 2;
		}
	}
 
 
	public class Passenger
	{
		public virtual void CheckPoint()
		{
			Console.WriteLine("Check passport");
		}
	}
 
	public class Europian : Passenger
	{
		
	}
 
	public class NonEuropian : Passenger
	{
		public override void CheckPoint()
		{
			base.CheckPoint();
			Console.WriteLine("Check Visa");
		}
	}