Java Reference
In-Depth Information
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 9.7 demonstrates how to use instance and static variables and meth-
ods and illustrates the effects of using them.
L
ISTING
9.7
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
CircleWithStaticMembers.numberOfObjects);
static variable
7
8
// Create c1
9
CircleWithStaticMembers c1 =
new
CircleWithStaticMembers();
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 ("
+
15
c1.numberOfObjects +
")"
);
static variable
16
17
// Create c2
18
CircleWithStaticMembers c2 =
new
CircleWithStaticMembers(
5
);
19
20
// Modify c1
21
c1.radius =
9
;
instance variable
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 c1.numberOfObjects +
")"
);
28 System.out.println(
"c2: radius ("
+ c2.radius +
29
static variable
") and number of Circle objects ("
+
30
c2.numberOfObjects +
")"
);
static variable
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)
When you compile
TestCircleWithStaticMembers.java
, the Java compiler automati-
cally compiles
CircleWithStaticMembers.java
if it has not been compiled since the last
change.
Static variables and methods can be accessed without creating objects. Line 6 displays the
number of objects, which is
0
, since no objects have been created.
Search WWH ::
Custom Search