Java Reference
In-Depth Information
Note that if you replace the preceding code with the following new code, the program would
be fine, because the instance data field
i
and method
m1
are now accessed from an object
a
(lines 7-8):
1
public class
A {
2
int
i =
5
;
3
static int
k =
2
;
4
5
public static void
main(String[] args) {
6 A a =
new
A();
7
int
j = a.i;
// OK, a.i accesses the object's instance variable
8
a.m1();
// OK. a.m1() invokes the object's instance method
9 }
10
11
public void
m1() {
12 i = i + k + m2(i, k);
13 }
14
15
public static int
m2(
int
i,
int
j) {
16
return
(
int
)(Math.pow(i, j));
17 }
18 }
Design Guide
How do you decide whether a variable or a method should be an instance one or a
static one? A variable or a method that is dependent on a specific instance of the class
should be an instance variable or method. A variable or a method that is not dependent
on a specific instance of the class should be a static variable or method. For example,
every circle has its own radius, so the radius is dependent on a specific circle. Therefore,
radius
is an instance variable of the
Circle
class. Since the
getArea
method is
dependent on a specific circle, it is an instance method. None of the methods in the
Math
class, such as
random
,
pow
,
sin
, and
cos
, is dependent on a specific instance.
Therefore, these methods are static methods. The
main
method is static and can be
invoked directly from a class.
instance or static?
Caution
It is a common design error to define an instance method that should have been defined
as static. For example, the method
factorial(int n)
should be defined as static,
as shown next, because it is independent of any specific instance.
common design error
public class
Test {
public int
factorial(
int
n) {
int
result =
1
;
for
(
int
i =
1
; i <= n; i ++)
result *= i;
public class
Test {
public static int
factorial(
int
n) {
int
result =
1
;
for
(
int
i =
1
; i <= n; i++)
result *= i;
return
result;
return
result;
}
}
}
}
(a) Wrong design
(b) Correct design
9.17
✓
✓
Suppose that the class
F
is defined in (a). Let
f
be an instance of
F
. Which of the
statements in (b) are correct?
Check
Point
Search WWH ::
Custom Search