Introduction

When you are creating a class, if you anticipate that a certain member should be redefined in a derived class, you can indicate this in your code. On the other hand, while creating a class that is based on another, if you find out that you are customizing a member that already exists in the base class, you should indicate, in your code, that you are providing a new version. In both cases, the common member is said to be a virtual member of the class.

Geometry - Square

Practical LearningPractical Learning: Introcing Abstraction

  1. Start Microsoft Visual Studio
  2. On the main menu, click File -> New -> Project...
  3. In the middle list, click ASP.NET Web Application (.NET Framework) and, in the Name text box, replace the name with Geometry08
  4. Click OK
  5. In the Solution Explorer, right-click Geometry08 -> Add -> Class...
  6. Change the file name to Square
  7. Click Add
  8. Change the document as follows:
    using System;
    
    namespace Geometry08
    {
        public class Square
        {
            public double Side { get; set; }
    
            public Square(double side)
            {
                Side = side;
            }
    
            public double Perimeter
            {
                get
                {
                    return Side * 4.00;
                }
            }
        }
    }

Virtual Methods

A method is said to be virtual if it is anticipated to have different versions or implementations in classes that derive from it. To create a virtual method, in the base class, type the virtual keyword to the left of the return type of the method. If the method has an access level (private, public, or internal), the virtual keyword can appear before or after the access level.

Practical LearningPractical Learning: Creating Virtual Methods

Virtual Properties

A property of a class is virtual if it may be implemented in a derived class. This means that the property should primarily be created in its original class.

To get a virtual property, when creating the class, add the virtual keyword before the return type of the property.

Practical LearningPractical Learning: Creating a Virtual Property

  1. Create a virtual property in the Square class as follows:
    using System;
    
    namespace Geometry08
    {
        public class Square
        {
            public double Side { get; set; }
    
            public Square(double side)
            {
                Side = side;
            }
    
            public double Perimeter
            {
                get
                {
                    return Side * 4.00;
                }
            }
    
            public virtual double Area
            {
                get
                {
                    return Side * Side;
                }
            }
            
            public virtual double CalculateInradius()
            {
                return Side / 2.00;
            }
    
            public virtual double CalculateCircumradius()
            {
                return Math.Sqrt(2.00) * Side / 2.00;
            }
        }
    }
  2. In the Solution Explorer, right-click Geometry08 -> Add -> Class...
  3. In the middle list, make sure Class is selected
    Change the name to Geometry
  4. Press Enter
  5. Change the code as follows:
    using static System.Console;
    
    namespace Geometry08
    {
        public class Geometry
        {
            private static void Main()
            {
                Square sqr = new Square(0.00);
                
                WriteLine("Geometry - Square");
                WriteLine("--------------------------");
                WriteLine("Enter the following values");
                Write("Side:    ");
                double side = double.Parse(ReadLine());
    
    
                sqr = new Square(side);
                Clear();
    
                WriteLine("Geometry - Square");
                WriteLine("-----------------------------------");
                WriteLine("Side:                 {0}", sqr.Side);
                WriteLine("-----------------------------------");
                WriteLine("Perimter:             {0}", sqr.Perimeter);
                WriteLine("Area:                 {0}", sqr.Area);
                WriteLine("Inscribed Radius:     {0}", sqr.CalculateInradius());
                WriteLine("Circumscribed Radius: " + sqr.CalculateCircumradius());
                WriteLine("===================================");
            }
        }
    }
  6. To execute the application to test the webpage, press Ctrl + F5:
    Geometry - Square
    --------------------------
    Enter the following values
    Side:
  7. For the Side value, type a number such as 429.63:
    Geometry - Square
    --------------------------
    Enter the following values
    Side:    429.63
  8. Press Enter:
    Geometry - Square
    -----------------------------------
    Side:                 429.63
    -----------------------------------
    Perimter:             1718.52
    Area:                 184581.9369
    Inscribed Radius:     214.815
    Circumscribed Radius: 303.794286401176
    ===================================
    Press any key to continue . . .
  9. Press Enter to close the window and return to your programming environment

    Creating a Virtual Method

  10. Save the following picture somewhere on your computer and return to your programming environment:
  11. On the main menu of Microsoft Visual Studio, click File -> New -> Project...
  12. In the middle list, click Empty Project (.NET Framework) and, in the Name text box, replace the name with Geometry09
  13. Click OK
  14. Click the Class View tab to activate it
  15. In the Solution Explorer, right-click Geometry09 -> Add -> Class...
  16. Change the name of the file to Trapezoid
  17. Click Add
  18. Change the class as follows:
    using static System.Math;
    
    namespace Geometry09
    {
        public class Trapezoid
        {
            public double ShortSide { get; set; }
            public double LongSide { get; set; }
            public double Edge { get; set; }
    
            public Trapezoid(double sSide, double lSide, double edge)
            {
                ShortSide = sSide;
                LongSide  = lSide;
                Edge      = edge;
            }
    
            public double Perimeter => LongSide + Edge + ShortSide + Edge;
    
            // http://mathworld.wolfram.com/IsoscelesTrapezoid.html
            public double Height
            {
                get
                {
                    return Sqrt((Edge * Edge) - (Pow(LongSide - ShortSide, 2.00) / 4.00));
                }
            }
    
            virtual public double CalculateArea()
            {
                return (LongSide + ShortSide) * Height / 2.00;
            }
        }
    }
  19. In the Solution Explorer, right-click Geometry09 -> Add -> Class...
  20. Type Geometry
  21. Press Enter
  22. Change the code as follows:
    using static System.Console;
    
    namespace Geometry09
    {
        public class Geometry
        {
            internal static int Main()
            {
                WriteLine("Geometry - Trapezoid");
                WriteLine("--------------------------");
                WriteLine("Enter the following values");
                Write("Short Side: ");
                double shortSide = double.Parse(ReadLine());
                Write("Long Side:  ");
                double longSide = double.Parse(ReadLine());
                Write("Edge:       ");
                double border = double.Parse(ReadLine());
    
                Trapezoid trap = new Trapezoid(sSide: shortSide, lSide: longSide, edge: border);
    
                Clear();
    
                WriteLine("Geometry - Trapezoid");
                WriteLine("--------------------------------");
                WriteLine("Short Side: {0}", trap.ShortSide);
                WriteLine("Long Side:  {0}", trap.LongSide);
                WriteLine("Border:     " + trap.Edge);
                WriteLine("--------------------------------");
                WriteLine("Height:     {0}", trap.Height);
                WriteLine("Perimter:   {0}", trap.Perimeter);
                WriteLine("Area:       {0}", trap.CalculateArea());
                WriteLine("================================");
    
                return 0;
            }
        }
    }
  23. To execute the project, on the main menu, click Debug -> Start Without Debugging:
    Geometry - Trapezoid
    --------------------------
    Enter the following values
    Short Side:
  24. For the Short Side value, type a number such as 137.96 and press Enter
  25. For the Long Side, type a number such as 209.73 and press Enter
  26. For the Edge, type a number such as 87.59
    Geometry - Trapezoid
    --------------------------
    Enter the following values
    Short Side: 137.96
    Long Side:  209.73
    Edge:       87.59
  27. Press Enter:
    Geometry - Trapezoid
    --------------------------------
    Short Side: 137.96
    Long Side:  209.73
    Border:     87.59
    --------------------------------
    Height:     79.9016575234832
    Perimter:   522.87
    Area:       13890.5036521699
    ================================
    Press any key to continue . . .
  28. Press Enter to close the window and return to your programming environment
  29. On the main menu of Microsoft Visual Studio, click File -> New -> Project...
  30. Make sure ASP.NET Web Application (.NET Framework) is selected in the middle list and, in the Name text box, replace the name with Geometry09
  31. Click OK
  32. In the Solution Explorer, right-click Geometry09 -> Add -> Class...
  33. Change the name of the file to Trapezoid
  34. Click Add
  35. Create the class as follows:
    using static System.Math;
    
    namespace Geometry09.App_Code
    {
        public class Trapezoid
        {
            public double ShortSide { get; set; }
            public double LongSide { get; set; }
            public double Edge { get; set; }
    
            public Trapezoid(double sSide, double lSide, double side)
            {
                ShortSide = sSide;
                LongSide = lSide;
                Edge = side;
            }
    
            public double Perimeter => LongSide + Edge + ShortSide + Edge;
    
            // http://mathworld.wolfram.com/IsoscelesTrapezoid.html
            public double Height
            {
                get
                {
                    return Sqrt((Edge * Edge) - (Pow(LongSide - ShortSide, 2.00) / 4.00));
                }
            }
    
            virtual public double CalculateArea()
            {
                return (LongSide + ShortSide) * Height / 2.00;
            }
        }
    }
  36. In the Solution Explorer, right-click Geometry09 -> Add -> Class...
  37. Type TrapezoidalPrism as the name of the class
  38. Click Add
  39. Change the class as follows:
    namespace Geometry09
    {
        public class TrapezoidalPrism : Trapezoid
        {
            public double Length { get; set; }
    
            public TrapezoidalPrism(double sSide, double lSide, double side, double len)
                : base(sSide, lSide, side)
            {
                Length = len;
            }
    
            public double BaseArea => base.CalculateArea();
    
            public double Volume => BaseArea * Length;
        }
    }

Overriding a Member in a Derived Class

As seen in previous sections, you can create a virtual method or property in a class and use it like any other method or property of its class. As mentioned in our introduction, the essence of creating a virtual method or property to provide a different implementation of that member in its own and in classes that derive from that class. Providing a different version of a member or property in a derived class is referred to as overriding the method or property.

To override a method, in a derived class, create a method with the same syntax (same return type, same name, and same parameter(s) if any) as the method in the parent class. This time, replace the virtual keyword with the override keyword. In the same way, to override a propertty, create one of the same return type and name in the derived class but use the override keyword instead of the the virtual keyword.

Practical LearningPractical Learning: Overriding a Method in a Derived Class

  1. In the TrapezoidalPrism class, override the CalculateArea() method as follows:
    namespace Geometry10
    {
        public class TrapezoidalPrism : Trapezoid
        {
            public double Length { get; set; }
    
            public TrapezoidalPrism(double sSide, double lSide, double side, double len)
                : base(sSide, lSide, side)
            {
                Length = len;
            }
    
            public double BaseArea => base.CalculateArea();
    
            override public double CalculateArea()
            {
                double shortArea = ShortSide * Length;
                double longArea = LongSide * Length;
                double sideArea = Edge * Length;
                return (BaseArea * 2.00) + shortArea + longArea + (sideArea * 2.00);
            }
    
            public double Volume => BaseArea * Length;
        }
    }
  2. In the Solution Explorer, right-click Geometry10 -> Add -> New Item...
  3. Type Geometry as the name of the class
  4. Press Enter
  5. Change the code as follows:
    using static System.Console;
    using static System.Environment;
    
    namespace Geometry02
    {
        public class Geometry
        {
            internal static int Main()
            {
                WriteLine("Geometry - Trapezoidal Prism");
                WriteLine("--------------------------");
                WriteLine("Enter the following values");
                Write("Short Side: ");
                double shortSide = double.Parse(ReadLine());
                Write("Long Side:  ");
                double longSide = double.Parse(ReadLine());
                Write("Edge:       ");
                double border = double.Parse(ReadLine());
                Write("Length:     ");
                double length = double.Parse(ReadLine());
    
                TrapezoidalPrism tp = new TrapezoidalPrism(shortSide, longSide, border, length);
    
                Clear();
    
                WriteLine("Geometry - Trapezoidal Prism");
                WriteLine("--------------------------------");
                Write("Short Side: {0}", tp.ShortSide + NewLine);
                Write("Long Side:  {0}", tp.LongSide + NewLine);
                Write("Edge:       " + tp.Edge + NewLine);
                Write("Length:     " + tp.Edge + NewLine);
                WriteLine("--------------------------------");
                Write("Base" + NewLine);
                WriteLine("Height:     {0}", tp.Height);
                WriteLine("Perimter:   {0}", tp.Perimeter);
                WriteLine("Base Area:  {0}", tp.BaseArea);
                WriteLine("--------------------------------");
                Write("Prism" + NewLine);
                WriteLine("Total Area: {0}", tp.CalculateArea());
                WriteLine("Volume:     {0}", tp.Volume);
                WriteLine("================================");
    
                return 0;
            }
        }
    }
  6. To execute the project, on the main menu, click Debug -> Start Without Debugging:
    Geometry - Trapezoidal Prism
    --------------------------
    Enter the following values
    Short Side:
  7. For the Short Side value, type a number such as 229.47 and press Enter
  8. For the Long Side, type a number such as 167.66 and press Enter
  9. For the Edge, type a number such as 98.59 and press Enter
  10. For the Length, type a number such as 214.85
    Geometry - Trapezoidal Prism
    --------------------------
    Enter the following values
    Short Side: 229.47
    Long Side:  167.66
    Edge:       98.59
    Length:     214.85
  11. Press Enter:
    Geometry - Trapezoidal Prism
    --------------------------------
    Short Side: 229.47
    Long Side:  167.66
    Edge:       98.59
    Length:     98.59
    --------------------------------
    Base
    Height:     93.6208794820899
    Perimter:   594.31
    Base Area:  18589.8299343612
    --------------------------------
    Prism
    Total Area: 164867.163368722
    Volume:     3994024.9613975
    ================================
    Press any key to continue . . .
  12. Press Enter to close the window and return to your programming environment
  13. Close your programming environment

Previous Copyright © 2002-2019, FunctionX Next