Java Reference
In-Depth Information
The
main
method creates two circles,
c1
and
c2
(lines 9, 18). The instance variable
radius
in
c1
is modified to become
9
(line 21). This change does not affect the instance
variable
radius
in
c2
, since these two instance variables are independent. The static vari-
able
numberOfObjects
becomes
1
after
c1
is created (line 9), and it becomes
2
after
c2
is
created (line 18).
Note that
PI
is a constant defined in
Math
, and
Math.PI
references the con-
stant.
c1.numberOfObjects
(line 27) and
c2.numberOfObjects
(line 30) are better
replaced by
CircleWithStaticMembers.numberOfObjects
. This improves readability,
because other programmers can easily recognize the static variable. You can also replace
CircleWithStaticMembers.numberOfObjects
with
CircleWithStaticMembers.
getNumberOfObjects()
.
Tip
Use
ClassName.methodName(arguments)
to invoke a static method and
ClassName.staticVariable
to access a static variable. This improves readability,
because this makes the static method and data easy to spot.
An instance method can invoke an instance or static method and access an instance or static
data field. A static method can invoke a static method and access a static data field. However,
a static method cannot invoke an instance method or access an instance data field, since static
methods and static data fields don't belong to a particular object. The relationship between
static and instance members is summarized in the following diagram:
use class name
invoke
invoke
An instance method
An instance method
access
access
An instance data field
An instance data field
An instance method
A static method
invoke
invoke
A static method
A static method
access
access
A static data field
A static data field
For example, the following code is wrong.
1
public class
A {
2
int
i =
5
;
3
static int
k =
2
;
4
5
public static void
main(String[] args) {
6
int
j = i;
// Wrong because i is an instance variable
7
m1();
// Wrong because m1() is an instance method
8 }
9
10
public void
m1() {
11
// Correct since instance and static variables and methods
12
// can be used in an instance method
13 i = i + k + m2(i, k);
14 }
15
16
public static int
m2(
int
i,
int
j) {
17
return
(
int
)(Math.pow(i, j));
18 }
19 }
Search WWH ::
Custom Search