C # basic -- virtual

Source: Internet
Author: User

Virtual keywords are used to modify methods, attributes, indexers, or event declarations, and enable them to be overwritten in a derived class.

When a virtual method is called, The runtime type of the object is checked for the override member.

Virtual modifiers cannot be used with static, abstract, private, or override modifiers.

  1. class TestClass{    public class Dimensions    {        public const double PI = Math.PI;        protected double x, y;        public Dimensions()        {        }        public Dimensions(double x, double y)        {            this.x = x;            this.y = y;        }        public virtual double Area()        {            return x * y;        }    }
  2.     public class Circle : Dimensions    {        public Circle(double r) : base(r, 0)        {        }        public override double Area()        {            return PI * x * x;        }    }    class Sphere : Dimensions    {        public Sphere(double r) : base(r, 0)        {        }        public override double Area()        {            return 4 * PI * x * x;        }    }    class Cylinder : Dimensions    {        public Cylinder(double r, double h) : base(r, h)        {        }        public override double Area()        {            return 2 * PI * x * x + 2 * PI * x * y;        }    }    static void Main()    {        double r = 3.0, h = 5.0;        Dimensions c = new Circle(r);        Dimensions s = new Sphere(r);        Dimensions l = new Cylinder(r, h);        Console.WriteLine("Area of Circle   = {0:F2}", c.Area());        Console.WriteLine("Area of Sphere   = {0:F2}", s.Area());        Console.WriteLine("Area of Cylinder = {0:F2}", l.Area());        Console.ReadLine();    }
  3. }

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.