Skip to content

2.4 Constructor chaining

  1. Change the code of the constructor with signature Circle(double radius) as follows:

    1
    2
    3
    public Circle(double radius) : this(radius, 0, 0, "white")
    {
    }
    

    Note that this(radius, 0, 0, "white") calls the all-args constructor within the class. The default values for centerX, centerY, and color are passed.

  2. Change the code of the default constructor Circle() as follows:

    1
    2
    3
    public Circle() : this(1)
    {
    }
    
    • this(1) now refers to the constructor with signature Circle(double radius) within the class. The default value for radius is passed.
    • The most generic constructor (the default constructor) calls the more specific constructor, which in turn calls the most specific constructor (the all-args constructor).
    • Note that every default value is determined in only one place.
  3. Modify the code in the Main method as follows:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    Circle myAllArgsCircle = new Circle(3, 1, 4, "green");
    Console.WriteLine(myAllArgsCircle.CalculatePerimeter());
    Console.WriteLine(myAllArgsCircle.CalculateArea());
    
    Circle myDefaultCircle = new Circle();
    Console.WriteLine(myDefaultCircle.CalculatePerimeter());
    Console.WriteLine(myDefaultCircle.CalculateArea());
    
    Circle myRadiusCircle = new Circle(6);
    Console.WriteLine(myRadiusCircle.CalculatePerimeter());
    Console.WriteLine(myRadiusCircle.CalculateArea());
    
  4. Run your program. Your output will look like this:

    1
    2
    3
    4
    5
    6
    18.84955592153876
    28.274333882308138
    6.283185307179586
    3.141592653589793
    37.69911184307752
    113.09733552923255
    

    Note that the output is the same as in Exercise 1.3.

  5. Try some other values and view the output.