Java Reference
In-Depth Information
25
/** Return the area of this circle */
26
double
getArea() {
27
return
radius * radius * Math.PI;
28 }
29 }
Method
getNumberOfObjects()
in
CircleWithStaticMembers
is a static method.
Other examples of static methods are
showMessageDialog
and
showInputDialog
in the
JOptionPane
class and all the methods in the
Math
class. The
main
method is static, too.
Instance methods (e.g.,
getArea()
) and instance data (e.g.,
radius
) belong to instances
and can be used only after the instances are created. They are accessed via a reference variable.
Static methods (e.g.,
getNumberOfObjects()
) and static data (e.g.,
numberOfObjects
)
can be accessed from a reference variable or from their class name.
The program in Listing 8.8 demonstrates how to use instance and static variables and
methods and illustrates the effects of using them.
L
ISTING
8.8
TestCircleWithStaticMembers.java
1
public class
TestCircleWithStaticMembers {
2
/** Main method */
3
public static void
main(String[] args) {
4 System.out.println(
"Before creating objects"
);
5 System.out.println(
"The number of Circle objects is "
+
6
static variable
CircleWithStaticMembers.numberOfObjects
);
7
8
// Create c1
CircleWithStaticMembers c1 =
new
CircleWithStaticMembers();
9
10
11
// Display c1 BEFORE c2 is created
12 System.out.println(
"\nAfter creating c1"
);
13 System.out.println(
"c1: radius ("
+ c1.radius +
14
instance variable
") and number of Circle objects ("
+
static variable
c1.numberOfObjects
15
+
")"
);
16
17
// Create c2
18
19
20
CircleWithStaticMembers c2 =
new
CircleWithStaticMembers(
5
);
// Modify c1
c1.radius =
9
;
instance variable
21
22
23
// Display c1 and c2 AFTER c2 was created
24 System.out.println(
"\nAfter creating c2 and modifying c1"
);
25 System.out.println(
"c1: radius ("
+ c1.radius +
26
") and number of Circle objects ("
+
27 +
")"
);
28 System.out.println(
"c2: radius ("
+ c2.radius +
29
c1.numberOfObjects
static variable
") and number of Circle objects ("
+
static variable
30
c2.numberOfObjects
+
")"
);
31 }
32 }
Before creating objects
The number of Circle objects is 0
After creating c1
c1: radius (1.0) and number of Circle objects (1)
After creating c2 and modifying c1
c1: radius (9.0) and number of Circle objects (2)
c2: radius (5.0) and number of Circle objects (2)