Skip to content

5.2 Polymorphism

  1. If needed, start from the project up to chapter 4. This contains the classes as you left them at the end of chapter 4.
  2. Create a new method in your Program class below your Main method:

    1
    2
    3
    4
    public static void ShowInformation(Shape shape)
    {
        Console.WriteLine(shape);
    }
    

    The parameter of this method is of type Shape.

  3. Change your Main method as follows:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    static void Main(string[] args)
    {
        Circle myCircle = new Circle(3, new Point(2, 5), "green");
        ShowInformation(myCircle);
        Console.WriteLine();
    
        Rectangle myRectangle = new Rectangle(3, 4, new Point(-2, 6), "blue");
        ShowInformation(myRectangle);
    }
    

    The ShowInformation() method is called with variables of type Circle and Rectangle. A method that expects a parameter of a base class can always be called with a variable of a derived class. This is called polymorphism.

  4. Run your program. Your output will look like this:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    Color: green
    Perimeter: 18.84955592153876
    Area: 28.274333882308138
    Radius: 3.0
    Center: (2.00, 5.00)
    
    Color: blue
    Perimeter: 14.0
    Area: 12.0
    Length: 3.0
    Width: 4.0
    Corner: (-2.00, 6.00)
    

    The first half of the output concerns the ToString() method of the Circle class. The second half concerns the ToString() method of the Rectangle class. The compiler determines which ToString() method to use. This is called dynamic binding.

    This principle can also be applied to arrays of a base class. Such an array can then hold objects of derived classes.

  5. Add the following lines to your Main method:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    Shape[] shapes = new Shape[3];
    shapes[0] = myCircle;
    shapes[1] = myRectangle;
    shapes[2] = new Circle(10, new Point(-1, -3), "crimson");
    
    for (int i = 0; i < 3; i++)
    {
        Console.WriteLine(shapes[i]);
        Console.WriteLine();
    }
    
  6. Run your program. The array contains objects of type Shape and can be filled with objects of any of the derived classes. The correct ToString() method is called for each.