Java Reference
In-Depth Information
There
are
times when we want a class simply to aggregate a few values, and
we should not hesitate to construct a class with public fields if that suits the pur-
pose. However, more usually, a class is developed for the
behavior
of its
instances: the fields are private, and all interaction with an instance is through
public methods. Classes
URL
,
JFrame
,
Date
, and
Employee
are examples of this;
they represent the more popular case.
In Fig. 3.6, we show a use of class
Coordinates
. Field
cent
of class
Circle
contains the center of a circle. There are four methods, which give the usual
properties of a circle: center, radius, diameter, and area. We have not used the
convention for getter-method names in naming these methods. In this case, the
more conventional names seem more appropriate. We leave the writing of a
toString
method for this class to you.
3.2.6
Self-review exercises
SR1.
Write a declaration (with no initialization) of two variables: one of class-
type String and another of class-type Employee.
SR2.
Write down the three steps in evaluating a new-expression (it is impor-
tant for future work that you memorize these three steps).
SR3.
Below is a new-expression. Evaluate it. In executing the constructor call,
step over
the call, i.e. execute it as an indivisible action based on what the spec-
ification of the constructor says. See Fig.3.1. What is the value of the call?
new
Employee("Clinton", 1996)
SR4.
Figure 3.6 contains a class
Circle
. What is wrong with this expression?
/**
An instance is a point
(x, y)
in the plane
*/
public class
Coordinates {
/**
The point is
(x, y) */
public int
x;
public int
y;
/**
Constructor: an instance for point
(x,y) */
public
Coordinates(
int
x,
int
y) {
this
.x= x;
this
.y= y;
}
/** =
the String
"(x, y)" */
public
String toString() {
return
"(" + x + ", " + y + ")";
}
}
Figure 3.5:
Class
Coordinates
Search WWH ::
Custom Search