1 publicclass TestCircle {
2 /** Main method */
3 publicstaticvoid main(String[] args) {
4 // Create a circle with radius 1
5 Circle circle1 = new Circle();
6 System.out.println("The area of the circle of radius "
7 + circle1.radius + " is " + circle1.getArea());
8
9 // Create a circle with radius 25
10 Circle circle2 = new Circle(25);
11 System.out.println("The area of the circle of radius "
12 + circle2.radius + " is " + circle2.getArea());
13
14 // Create a circle with radius 125
15 Circle circle3 = new Circle(125);
16 System.out.println("The area of the circle of radius "
17 + circle3.radius + " is " + circle3.getArea());
18
19 // Modify circle radius
20 circle2.radius = 100; // or circle2.setRadius(100)
21 System.out.println("The area of the circle of radius "
22 + circle2.radius + " is " + circle2.getArea());
23 }
24 }
25
26 // Define the circle class with two constructors
27 class Circle {
28 double radius;
29
30 /** Construct a circle with radius 1 */
31 Circle() {
32 radius = 1;
33 }
34
35 /** Construct a circle with a specified radius */
36 Circle(double newRadius) {
37 radius = newRadius;
38 }
39
40 /** Return the area of this circle */
41 double getArea() {
42 return radius * radius * Math.PI;
43 }
44
45 /** Return the perimeter of this circle */
46 double getPerimeter() {
47 return2 * radius * Math.PI;
48 }
49
50 /** Set a new radius for this circle */
51 void setRadius(double newRadius) {
52 radius = newRadius;
53 }
54 }