Home

Polymorphism

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 should be created as virtual.

Practical LearningPractical Learning: Introcing Abstraction

  1. Start Microsoft Visual Studio. On the Visual Studio 2019 dialog box, click Create a New Project (if Microsoft Visual Studio was already opened, on the main menu, click File -> New Project...)
  2. In the list of projects templates of the Create New Project dialog box, click Windows Forms App (.NET Framework)
  3. Click Next
  4. Replace the suggested name of the project with Geometry15
  5. Press Enter
  6. In the Solution Explorer, right-click Geometry12 -> Add -> Class...
  7. Change the file name to Square
  8. Click Add
  9. Change the document as follows:
    using System;
    
    namespace Geometry15
    {
        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 Geometry15
    {
        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. Save the following picture somewhere on your computer and return to your programming environment:

    Geometry - Square

  3. In the Solution Explorer, double-click Form1.cs
  4. Design the form as follows:

    Virtual Properties

    Control (Name) Text Other Properties
    PictureBox     Image: Square
    Label   Geometry - Square Font: Georgia, 20, Bold
    Label   ____________  
    Label   Side  
    TextBox txtSide    
    Button btnCalculate Calculate  
    Label   Perimeter:  
    TextBox txtPerimeter    
    Label   Area:  
    TextBox txtArea    
    Label   Inscribed Radius:  
    TextBox txtInscribedRadius    
    Label   Circumscribed Radius:  
    TextBox txtCircumscribedRadius    
  5. Double-click the Calculate button
  6. Change the code as follows:
    using System;
    using System.Windows.Forms;
    
    namespace Geometry15
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void btnCalculate_Click(object sender, EventArgs e)
            {
                double side = 0.00;
    
                try
                {
                    side = Convert.ToDouble(txtSide.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("You must provide a valid value for the side of the square.", "Geometry - Square");
                }
                
                Square sqr = new Square(side);
    
                txtPerimeter.Text = sqr.Perimeter.ToString();
                txtArea.Text  =sqr.Area.ToString();
                txtInscribedRadius.Text  =sqr.CalculateInradius().ToString();
                txtCircumscribedRadius.Text = sqr.CalculateCircumradius().ToString();
            }
        }
    }
  7. To execute the application to test the webpage, press Ctrl + F5:

    Virtual Properties

  8. In the Side text box, type a number such as 429.63:

    Virtual Properties

  9. Click the Calculate button:

    Virtual Properties

  10. Close the browser and return to your programming environment
  11. Save the following picture somewhere on your computer and return to your programming environment:

    Creating a Virtual Method

  12. On the main menu of Microsoft Visual Studio, click File -> New -> Project...
  13. In the list of projects templates, click Windoes Forms App (.NET Framework)
  14. Click Next
  15. Replace the name of the project with Geometry16
  16. Press Enter
  17. In the Solution Explorer, right-click Geometry13 -> Add -> Class...
  18. Change the name of the file to Trapezoid
  19. Click Add
  20. Change the class as follows:
    using System;
    
    namespace Geometry16
    {
        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 Math.Sqrt((Edge * Edge) - (Math.Pow(LongSide - ShortSide, 2.00) / 4.00));
                }
            }
    
            virtual public double CalculateArea()
            {
                return (LongSide + ShortSide) * Height / 2.00;
            }
        }
    }
  21. In the Solution Explorer, right-click Form1.cs -> View Designer
  22. Design the form as follows:

    Virtual Properties

    Control (Name) Text Other Properties
    PictureBox     Image: Trapezoid
    Label   Geometry - Square Font: Georgia, 20, Bold
    Label   _______________  
    Label   Short Side:  
    TextBox txtShortSide    
    Label   Long Side:  
    TextBox txtLongSide    
    Label   Edge:  
    TextBox txtEdge    
    Button btnCalculate Calculate  
    Label   Height:  
    TextBox txtHeight    
    Label   Perimeter:  
    TextBox txtPerimeter    
    Label   Area:  
    TextBox txtArea    
  23. Double-click the Calculate button
  24. Change the code as follows:
    using System;
    using System.Windows.Forms;
    
    namespace Geometry16
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void btnCalculate_Click(object sender, EventArgs e)
            {
                Trapezoid shape = CreateShape();
    
                Show(shape);
            }
    
            void Show(object obj)
            {
                if (obj is null)
                    return;
    
                if(obj is Trapezoid)
                {
                    Trapezoid brick = (Trapezoid)obj;
    
                    txtHeight.Text = brick.Height.ToString();
                    txtPerimeter.Text = brick.Perimeter.ToString();
                    txtArea.Text = brick.CalculateArea().ToString();
                }
            }
    
            Trapezoid CreateShape()
            {
                double border = 0.00;
                double longSide = 0.00;
                double shortSide = 0.00;
                Trapezoid trap = new Trapezoid(sSide: 0.00, lSide: 0.00, edge: 0.00);
    
                try
                {
                    shortSide = Convert.ToDouble(txtShortSide.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("You must provide a valid value for the short side of the trapezoid.", "Geometry - Trapezoid");
                }
    
                try
                {
                    longSide = Convert.ToDouble(txtLongSide.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("Make sure must provide a valid value for the short side of the trapezoid.", "Geometry - Trapezoid");
                }
    
                try
                {
                    border = Convert.ToDouble(txtEdge.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("If you forgot, or did sure must provide a valid value for the short side of the trapezoid.", "Geometry - Trapezoid");
                }
    
                trap = new Trapezoid(sSide: shortSide, lSide: longSide, border);
    
                return trap;
            }
        }
    }
  25. To execute the project, on the main menu, click Debug -> Start Without Debugging:

    Displaying a Picture in a Control

  26. In the Short Side text box, enter a number such as 137.96
  27. In the Long Side text box, enter a number such as 209.73
  28. In the Edge text box, enter a number such as 87.59

    Displaying a Picture in a Control

  29. Click the Calculate button:

    Displaying a Picture in a Control

  30. Close the browser and return to your programming environment
  31. On the main menu of Microsoft Visual Studio, click File -> New -> Project...
  32. In the list of projects templates, click Windows Forms App (.NET Framework)
  33. Click Next
  34. Replace the project name with Geometry17
  35. Press Enter
  36. In the Solution Explorer, right-click the name of the project -> Add -> Class...
  37. Change the name of the file to Trapezoid
  38. Click Add
  39. Fill the class as follows:
    using static System.Math;
    
    namespace Geometry17
    {
        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;
            }
        }
    }
  40. In the Solution Explorer, right-click App_Code -> Add -> Class...
  41. Set the name of the class as TrapezoidalPrism
  42. Click Add
  43. Change the class as follows:
    namespace Geometry17
    {
        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 is 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 Geometry17
    {
        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 Form1.cs and click View Designer
  3. Design the form as follows:

    Virtual Properties

    Control (Name) Text Font
    Label   Geometry - Trapezoid Font: Times New Roman, 24, Bold
    Label   _______________ Georgia, 20.25pt, style=Bold, Italic
    PictureBox     Image: Trapezoid
    Label   Base ______________  
    Label   Short Side:  
    TextBox txtShortSide    
    Label   Long Side:  
    TextBox txtLongSide    
    Label   Edge:  
    TextBox txtEdge    
    Label   Prism ______________  
    Label   Length:  
    TextBox txtLength    
    Button btnCalculate Calculate  
    Label   Base ______________  
    Label   Height:  
    TextBox txtHeight    
    Label   Perimeter:  
    TextBox txtPerimeter    
    Label   Base Area:  
    TextBox txtBaseArea    
    Label   Prism ______________  
    Label   Total Area:  
    TextBox txtTotalArea    
    Label   Volume:  
    TextBox txtVolume    
  4. Double-click the Calculate button
  5. Change the document as follows:
    using System;
    using System.Windows.Forms;
    
    namespace Geometry17
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            TrapezoidalPrism GetValue()
            {
                double edge = 0.00;
                double length = 0.00;
                double longSide = 0.00;
                double shortSide = 0.00;
                TrapezoidalPrism tp = new TrapezoidalPrism(shortSide, longSide, edge, length);
    
                try
                {
                    shortSide = Convert.ToDouble(txtShortSide.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("Make sure you provide a valid value for the short side.", "Geometry - Trapezoidal Prism");
                }
    
                try
                {
                    longSide = Convert.ToDouble(txtLongSide.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("You must enter a value for the long side.", "Geometry - Trapezoidal Prism");
                }
    
                try
                {
                    edge = Convert.ToDouble(txtEdge.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("You are supposed to type an appropriate value for the edge.", "Geometry - Trapezoidal Prism");
                }
    
                try
                {
                    length = Convert.ToDouble(txtLength.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("You are supposed to type an appropriate value for the edge.", "Geometry - Trapezoidal Prism");
                }
    
                return new TrapezoidalPrism(shortSide, longSide, edge, length);
            }
    
            void Display(TrapezoidalPrism prism)
            {
                if (prism is null)
                    return;
    
                txtHeight.Text = prism.Height.ToString();
                txtPerimeter.Text= prism.Perimeter.ToString();
                txtBaseArea.Text = prism.BaseArea.ToString();
                txtTotalArea.Text = prism.CalculateArea().ToString();
                txtVolume.Text = prism.Volume.ToString();
            }
    
            private void btnCalculate_Click(object sender, EventArgs e)
            {
                TrapezoidalPrism tp = GetValue();
    
                Display(tp);
            }
        }
    }
  6. To execute the project, on the main menu, click Debug -> Start Without Debugging:

    Overriding a Method in a Derived Class

  7. In the Short Side text box, enter a number such as 229.47
  8. In the Long Side text box, enter a number such as 167.66
  9. In the Edge text box, enter a number such as 98.59
  10. In the Length text box, enter a number such as 214.85

    Overriding a Method in a Derived Class

  11. Click the Calculate button:

    Overriding a Method in a Derived Class

  12. Close the form and return to your programming environment
  13. Close your programming environment

Previous Copyright © 2002-2021, FunctionX Next