Java Reference
In-Depth Information
b
r
a
h
c
w
Figure 9.4
Three types of shapes
There is an is-a relationship here, because a rectangle, a circle, and a triangle are
all shapes. But code sharing isn't useful in this case because each class implements
its behavior differently. As depicted in Figure 9.4 and Table 9.12, each shape com-
putes its area and perimeter in a totally different way. The w and h represent the
rectangle's width and height; the r represents the circle's radius; and the a , b , and c
represent the lengths of the triangle's three sides.
Since no code is shared among these classes, we should not create a common
superclass to represent their is-a relationship. Java uses single inheritance, and we
don't want to use up our only potential inheritance relationship here. A better solu-
tion would be to write an interface called Shape to represent the common functional-
ity of all shapes: the ability to ask for an area and a perimeter. Our various shape
classes will implement this interface.
To write an interface, we create a new file with the same name as the interface's
name; our Shape interface, for example, would be stored in Shape.java . We give
the interface a header with the keyword interface in place of the word class :
public interface Shape {
...
}
Inside the interface, we write headers for each method that we want a Shape to
contain. But instead of writing method bodies with braces, we simply place a
semicolon at the end of each header. We don't specify how the methods are imple-
mented. Instead, we're requiring that any class that wants to be considered a shape
must implement these methods. In fact, it isn't legal for an interface to contain
method bodies; an interface can only contain method headers and class constants.
Table 9.12
Formulas for Area and Perimeter of Each Shape Type
Rectangle
Circle
Triangle
Area
w * h
π
r 2
1
s ( s
-
a )( s
-
b )( s
-
c )
a
+
b
+
c
where
s
=
2
Perimeter
2 ( w
h )
2
π
r
a
b
c
 
 
Search WWH ::




Custom Search