Difference between virtual and abstract methods

This question already has an answer here:

  • What is the difference between an abstract function and a virtual function? 21 answers

  • Virtual methods have an implementation and provide the derived classes with the option of overriding it. Abstract methods do not provide an implementation and force the derived classes to override the method.

    So, abstract methods have no actual code in them, and subclasses HAVE TO override the method. Virtual methods can have code, which is usually a default implementation of something, and any subclasses CAN override the method using the override modifier and provide a custom implementation.

    public abstract class E
    {
        public abstract void AbstractMethod(int i);
    
        public virtual void VirtualMethod(int i)
        {
            // Default implementation which can be overridden by subclasses.
        }
    }
    
    public class D : E
    {
        public override void AbstractMethod(int i)
        {
            // You HAVE to override this method
        }
        public override void VirtualMethod(int i)
        {
            // You are allowed to override this method.
        }
    }
    

    First of all you should know the difference between a virtual and abstract method.

    Abstract Method

  • Abstract Method resides in abstract class and it has no body.
  • Abstract Method must be overridden in non-abstract child class.
  • Virtual Method

  • Virtual Method can reside in abstract and non-abstract class.
  • It is not necessary to override virtual method in derived but it can be.
  • Virtual method must have body ....can be overridden by "override keyword".....

  • an abstract method must be call override in derived class other wise it will give compile-time error and in virtual you may or may not override it's depend if it's good enough use it

    Example:

    abstract class twodshape
    {
        public abstract void area(); // no body in base class
    }
    
    class twodshape2 : twodshape
    {
        public virtual double area()
        {
            Console.WriteLine("AREA() may be or may not be override");
        }
    }
    
    链接地址: http://www.djcxy.com/p/38112.html

    上一篇: 抽象和虚拟有什么区别?

    下一篇: 虚拟和抽象方法之间的区别