5.2 Polymorphism
- If needed, start from the project up to chapter 4. This contains the classes as you left them at the end of chapter 4.
-
Create a new method in your
Programclass below yourMainmethod:1 2 3 4
public static void ShowInformation(Shape shape) { Console.WriteLine(shape); }The parameter of this method is of type
Shape. -
Change your
Mainmethod 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 typeCircleandRectangle. 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. -
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 theCircleclass. The second half concerns theToString()method of theRectangleclass. The compiler determines whichToString()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.
-
Add the following lines to your
Mainmethod: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(); } -
Run your program. The array contains objects of type
Shapeand can be filled with objects of any of the derived classes. The correctToString()method is called for each.