Skip to content

4.3 Inheritance: the Circle derived class

  1. Change the class definition of Circle as follows:

    1
    2
    public class Circle : Shape
    {
    

    The code : Shape says that the Circle class is now a derived class of the Shape class. All attributes and methods that are public or protected within the Shape class are now also available to the Circle class.

  2. Remove the line:

    1
    private const double LimitValueForBigShape = 100.0;
    
    The constant is now inherited from the Shape class.

  3. Remove the line:

    1
    private string _color;
    
    The attribute is also inherited from the Shape class.

  4. Modify the all-args constructor as follows:

    1
    2
    3
    4
    5
    public Circle(double radius, Point center, string color) : base(color)
    {
        _radius = radius;
        _center = center;
    }
    

    color is an attribute of the Shape class. base refers to the base (super) class. base(color) calls the all-args constructor of the Shape class.

  5. Modify the radius constructor as follows:

    1
    2
    3
    public Circle(double radius) : this(radius, new Point(), DefaultColor)
    {
    }
    

    The Shape class determines the default value for color. This is used in the constructor chaining.

  6. Add the override keyword to the CalculatePerimeter() and CalculateArea() methods:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    public override double CalculatePerimeter()
    {
        return 2 * Math.PI * _radius;
    }
    
    public override double CalculateArea()
    {
        return Math.PI * _radius * _radius;
    }
    

    override indicates that the original methods in the Shape class are not used in the derived Circle class. Instead, the class's own methods are used. Note that the keyword is optional for correctness but improves readability.

  7. Remove the entire DescribeSize() method from the Circle class. The method in the Shape class is now used and it is not necessary to have a separate implementation.

  8. Remove the entire Color getter and setter. These are also inherited from the Shape class.

  9. In the Main method, go to the line with Console.WriteLine(myCircleArray[i].Center.Y); and add an empty line.

  10. Type Console.WriteLine(myCircleArray[i] and then a period. You will see that the method DescribeSize() is available in the Circle class. Also Color getter and setter are available.

  11. Select the method DescribeSize().

  12. Comment out the entire code about the rectangle.