Java Reference
In-Depth Information
Heron's formula which says that the area of a triangle with sides of lengths a , b , and
c is related to a value s that is equal to half the triangle's perimeter:
a
+
b
+
c
area
= 1
s ( s
-
a )( s
-
b )( s
-
c )
where
s
=
2
Here is a complete version of the Triangle class:
1 // Represents triangular shapes.
2 public class Triangle implements Shape {
3 private double a;
4 private double b;
5 private double c;
6
7 // constructs a new triangle with the given side lengths
8 public Triangle( double a, double b, double c) {
9 this .a = a;
10 this .b = b;
11 this .c = c;
12 }
13
14 // returns this triangle's area using Heron's formula
15 public double getArea() {
16 double s = (a + b + c) / 2.0;
17 return Math.sqrt(s * (s - a) * (s - b) * (s - c));
18 }
19
20 // returns the perimeter of this triangle
21 public double getPerimeter() {
22 return a + b + c;
23 }
24 }
Using these shape classes and their common interface, a client program can now
construct an array of shapes, write a method that accepts a general shape as a param-
eter, and otherwise take advantage of polymorphism.
Benefits of Interfaces
Classes that implement a common interface form a type hierarchy similar to those
created by inheritance. The interface serves as a parent type for the classes that
implement it. The following diagram represents our type hierarchy after our modifi-
cations. The way we represent an interface is similar to the way we represent a class,
but we use the word “interface” for clarity. The methods are italicized to emphasize
that they are abstract. Figure 9.5 shows our use of dashed lines to connect the classes
and the interface they implement.
 
 
Search WWH ::




Custom Search