Java Reference
In-Depth Information
Enter point1's x-, y-coordinates: 1.5 5.5
Enter point2's x-, y-coordinates: -5.3 -4.4
p1 is Point2D [x = 1.5, y = 5.5]
p2 is Point2D [x = -5.3, y = -4.4]
The distance between p1 and p2 is 12.010412149464313
This program creates two objects of the
Point2D
class (lines 15-16). The
toString()
method returns a string that describes the object (lines 17-18). Invoking
p1.distance(p2)
returns the distance between the two points (line 20).
9.14
✓
✓
How do you create a
Date
for the current time? How do you display the current time?
Check
9.15
How do you create a
Point2D
? Suppose
p1
and
p2
are two instances of
Point2D
?
How do you obtain the distance between the two points?
Point
9.16
Which packages contain the classes
Date
,
Random
,
Point2D
,
System
, and
Math
?
A static variable is shared by all objects of the class. A static method cannot access
instance members of the class.
Key
Point
The data field
radius
in the circle class is known as an
instance variable
. An instance vari-
able is tied to a specific instance of the class; it is not shared among objects of the same class.
For example, suppose that you create the following objects:
Static vs. instance
instance variable
Circle circle1 =
new
Circle();
Circle circle2 =
new
Circle(
5
);
VideoNote
Static vs. instance
The
radius
in
circle1
is independent of the
radius
in
circle2
and is stored in a differ-
ent memory location. Changes made to
circle1
's
radius
do not affect
circle2
's
radius
,
and vice versa.
If you want all the instances of a class to share data, use
static variables
, also known as
class variables
. Static variables store values for the variables in a common memory location.
Because of this common location, if one object changes the value of a static variable, all
objects of the same class are affected. Java supports static methods as well as static variables.
Static methods
can be called without creating an instance of the class.
Let's modify the
Circle
class by adding a static variable
numberOfObjects
to count the
number of circle objects created. When the first object of this class is created,
numberOfOb-
jects
is
1
. When the second object is created,
numberOfObjects
becomes
2
. The UML
of the new circle class is shown in Figure 9.13. The
Circle
class defines the instance vari-
able
radius
and the static variable
numberOfObjects
, the instance methods
getRadius
,
setRadius
, and
getArea
, and the static method
getNumberOfObjects
. (Note that static
variables and methods are underlined in the UML class diagram.)
To declare a static variable or define a static method, put the modifier
static
in the
variable or method declaration. The static variable
numberOfObjects
and the static method
getNumberOfObjects()
can be declared as follows:
static variable
static method
static int
numberOfObjects;
declare static variable
static int
getNumberObjects() {
return
numberOfObjects;
define static method
}
Search WWH ::
Custom Search