Java Reference
In-Depth Information
This is wrong, because the private data fields
color
and
filled
in the
GeometricObject
class cannot be accessed in any class other than in the
GeometricObject
class itself. The
only way to read and modify
color
and
filled
is through their getter and setter methods.
The
Rectangle
class (ListingĀ 11.3) extends the
GeometricObject
class (ListingĀ 11.1)
using the following syntax:
Subclass
Superclass
public class
Rectangle
extends
GeometricObject
The keyword
extends
(lines 1-2) tells the compiler that the
Rectangle
class extends the
GeometricObject
class, thus inheriting the methods
getColor
,
setColor
,
isFilled
,
setFilled
, and
toString
.
L
ISTING
11.3
RectangleFromSimpleGeometricObject.java
1
public class
RectangleFromSimpleGeometricObject
2
extends
SimpleGeometricObject {
extends superclass
data fields
3
private double
width;
4
private double
height;
5
6
public
RectangleFromSimpleGeometricObject() {
7 }
8
9
constructor
public
RectangleFromSimpleGeometricObject(
10
double
width,
double
height) {
11
this
.width = width;
12
this
.height = height;
13 }
14
15
public
RectangleFromSimpleGeometricObject(
16
double
width,
double
height, String color,
boolean
filled) {
17
this
.width = width;
18
this
.height = height;
19 setColor(color);
20 setFilled(filled);
21 }
22
23
/** Return width */
24
public double
getWidth() {
methods
25
return
width;
26 }
27
28
/** Set a new width */
29
public void
setWidth(
double
width) {
30
this
.width = width;
31 }
32
33
/** Return height */
34
public double
getHeight() {
35
return
height;
36 }
37
38
/** Set a new height */
39
public void
setHeight(
double
height) {
40
this
.height = height;
41 }
Search WWH ::
Custom Search