Java Reference
In-Depth Information
SR6 . Given n≥2 , write a loop that sets boolean value b to the value of the sen-
tence “no integer in the range 2..(n - 1) divides n ”. Make sure you test your
answer for various values of n .
SR7 . Given n≥1 , write a loop that stores in x the sum of the first n values of
this sequence: 1 , 2 , -3 , 4 , 5 , -6 , 7 , 8 , -9 , .
2.4
Static versus non-static methods
The purpose of this section is to make clear, once more, the difference between
static and non-static components of a class. This material is placed here for com-
pleteness, so that everything about methods is in this one Chap. 2. We assume
that you know about class definitions and how to draw an instance (manila fold-
er) of a class.
Below is a class that contains a static method called staticMethod and a
static variable staticVar , as well as a non-static method called nonStatic-
Method and variable nonStaticVar :
public class C {
static int staticVar;
int nonStaticVar;
static void staticMethod( int x) {...}
void nonStaticMethod( int y) {...}
}
The distinction between static and non-static components is simple: static
components go directly into the file drawer for the class, while non-static com-
ponents appear in each and every instance of the class. Figure 2.6 illustrates this,
showing a filing cabinet with a drawer named C and, to its right, the contents of
the drawer. Static components staticVar and staticMethod are in the drawer.
The drawer also contains two instances of class C . (We would create them using
new -expressions.) Note that both instances contain a field nonStaticVar and a
method nonStaticMethod because these are defined to be non-static.
staticMethod( int )
staticVar
a1
a2
C
C
nonStaticVar
nonStaticVar
nonStaticMethod( int )
nonStaticMethod( int )
Contents of C 's file drawer
Figure 2.6:
The file drawer for class C
Search WWH ::




Custom Search