Java Reference
In-Depth Information
17 }
18
19
/** Return radius */
20
public double
getRadius() {
methods
21
return
radius;
22 }
23
24
/** Set a new radius */
25
public void
setRadius(
double
radius) {
26
this
.radius = radius;
27 }
28
29
/** Return area */
30
public double
getArea() {
31
return
radius * radius * Math.PI;
32 }
33
34
/** Return diameter */
35
public double
getDiameter() {
36
return
2
* radius;
37 }
38
39
/** Return perimeter */
40
public double
getPerimeter() {
41
return
2
* radius * Math.PI;
42 }
43
44
/** Print the circle info */
45
public void
printCircle() {
46 System.out.println(
"The circle is created "
+ getDateCreated() +
47
" and the radius is "
+ radius);
48 }
49 }
The
Circle
class (ListingĀ 11.2) extends the
GeometricObject
class (ListingĀ 11.1) using
the following syntax:
Subclass
Superclass
public class
Circle
extends
GeometricObject
The keyword
extends
(lines 1-2) tells the compiler that the
Circle
class extends the
GeometricObject
class, thus inheriting the methods
getColor
,
setColor
,
isFilled
,
setFilled
, and
toString
.
The overloaded constructor
Circle(double radius, String color, boolean
filled)
is implemented by invoking the
setColor
and
setFilled
methods to set the
color
and
filled
properties (lines 12-17). These two public methods are defined in the superclass
GeometricObject
and are inherited in
Circle
, so they can be used in the
Circle
class.
You might attempt to use the data fields
color
and
filled
directly in the constructor as
follows:
private member in superclass
public
CircleFromSimpleGeometricObject(
double
radius, String color,
boolean
filled) {
this
.radius = radius;
this
.color = color;
// Illegal
this
.filled = filled;
// Illegal
}
Search WWH ::
Custom Search