2.2 Encapsulation
- If needed, start from the project up to chapter 1. This contains the classes
ProgramandCircleas you left them at the end of chapter 1. -
Change the code in the
Circleclass as follows:1 2 3 4
private double _radius; private double _centerX; private double _centerY; private string _color;privatemeans that the attribute or method is only available within the class itself. It is therefore no longer accessible fromProgram. -
Add getters and setters (properties) in the
Circleclass.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. -
Modify the
Mainmethod 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()); } -
Run your program. Your output will look like this:
1 2 3 4 5
1.0 6.283185307179586 3.141592653589793 18.84955592153876 28.274333882308138 -
Try some other values and view the output.