Java Reference
In-Depth Information
figure 4.12
Circle
and
Rectangle
classes
1
public class Circle extends Shape
2
{
3
public Circle( double rad )
4
{ radius = rad; }
5
6
public double area( )
7
{ return Math.PI * radius * radius; }
8
9
public double perimeter( )
10
{ return 2 * Math.PI * radius; }
11
12
public String toString( )
13
{ return "Circle: " + radius; }
14
15
private double radius;
16
}
17
18
public class Rectangle extends Shape
19
{
20
public Rectangle( double len, double wid )
21
{ length = len; width = wid; }
22
23
public double area( )
24
{ return length * width; }
25
26
public double perimeter( )
27
{ return 2 * ( length + width ); }
28
29
public String toString( )
30
{ return "Rectangle: " + length + " " + width; }
31
32
public double getLength( )
33
{ return length; }
34
35
public double getWidth( )
36
{ return width; }
37
38
private double length;
39
private double width;
40
}
The programmer has attempted to signal that calling
Shape
's area is an
error by returning -1, which is an obviously impossible area. But this is a
value that might be ignored. Furthermore, this is a value that will be returned
if, when extending
Shape
,
area
is not overridden. This failure to override could
occur because of a typographical error: An
Area
function is written instead of
area
, making it difficult to track down the error at run time.
Search WWH ::
Custom Search