Sunday, 11 June 2017

What is the difference between an abstract method and a virtual method?


Abstract Method
  1. Abstract method is defined in only abstract class.
  2. Abstract method should contain only method definition (No Implementation).
  3. Abstract method must be override in the derived class.
Virtual Method
  1. Virtual methods may or may not override in the derived class (not mandatory).
  2. Virtual methods must have implementation along with definition of method.



follow mention the implementation 





public abstract class BaseClass{
     public abstract decimal GetSumAbstractMethod(decimal value1, decimal value2);
     public virtual decimal GetSumVirtualMethod1(decimal value1, decimal value2)
     {
            return value1 + value2;
     }
    public virtual decimal GetSumVirtualMethod2(decimal value1, decimal value2)
    {
            return value1 + value2;
    }
}
 public class DerivedClass : BaseClass{
   public override decimal GetSumAbstractMethod(decimal value1, decimal value2)
   {
            return value1 + value2;
   }
   public override decimal GetSumVirtualMethod2(decimal value1, decimal value2)
   {
            return (value1 + value2) *2 ;
   }
   public void ImplementationMethods()
   {
            DerivedClass derivedClass = new DerivedClass();
            derivedClass.GetSumAbstractMethod(1, 2);
            derivedClass.GetSumVirtualMethod1(1, 2);
            derivedClass.GetSumVirtualMethod2(1, 2);
   }
}


No comments:

Post a Comment

Single Responsibility Principle (SRP)