Java Reference
In-Depth Information
11
12 // returns the area of this rectangle
13 public double getArea() {
14 return width * height;
15 }
16
17 // returns the perimeter of this rectangle
18 public double getPerimeter() {
19 return 2.0 * (width + height);
20 }
21 }
The other classes of shapes are implemented in a similar fashion. We'll define a
Circle object to have a field called radius . (We'll abandon the center Point object
used in the Circle class earlier in the chapter, since we don't need it here.) We can
determine the area by multiplying
π
by the radius squared. To find the perimeter, we'll
use the equation 2 *
* r . Notice that there is no common code between Circle
and Rectangle , so inheritance is unnecessary. Here is the complete Circle class:
π
1 // Represents circular shapes.
2 public class Circle implements Shape {
3 private double radius;
4
5 // constructs a new circle with the given radius
6 public Circle( double radius) {
7 this .radius = radius;
8 }
9
10 // returns the area of this circle
11 public double getArea() {
12 return Math.PI * radius * radius;
13 }
14
15 // returns the perimeter of this circle
16 public double getPerimeter() {
17 return 2.0 * Math.PI * radius;
18 }
19 }
Finally, we'll specify a triangle's shape by its three side lengths, a , b , and c.
The perimeter of the triangle is simply the sum of the three side lengths. The
getArea method is a bit trickier, but there is a useful geometric formula called
 
Search WWH ::




Custom Search