Skip to content

2.2 Encapsulation

  1. If needed, start from the project up to chapter 1. This contains the classes Program and Circle as you left them at the end of chapter 1.
  2. Change the code in the Circle class as follows:

    1
    2
    3
    4
    private double _radius;
    private double _centerX;
    private double _centerY;
    private string _color;
    

    private means that the attribute or method is only available within the class itself. It is therefore no longer accessible from Program.

  3. Add getters and setters (properties) in the Circle class.

    TIP: You can easily add properties by right-clicking the fields, selecting Quick Actions and Refactorings, then Encapsulate fields. Or use CTRL+. and choose Generate property.

  4. Modify the Main method as follows:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    static void Main(string[] args)
    {
        Circle myDefaultCircle = new Circle();
        Console.WriteLine(myDefaultCircle.Radius);
        Console.WriteLine(myDefaultCircle.CalculatePerimeter());
        Console.WriteLine(myDefaultCircle.CalculateArea());
        myDefaultCircle.Radius = 3;
        Console.WriteLine(myDefaultCircle.CalculatePerimeter());
        Console.WriteLine(myDefaultCircle.CalculateArea());
    }
    
  5. Run your program. Your output will look like this:

    1
    2
    3
    4
    5
    1.0
    6.283185307179586
    3.141592653589793
    18.84955592153876
    28.274333882308138
    
  6. Try some other values and view the output.