Java Reference
In-Depth Information
Compare Static to Global
Java does not allow global methods; all methods must be defi ned within a class.
A static method is the closest thing we have in Java to creating a global function. They
are utility methods that perform their task only with the arguments passed in or with
other “global” data like static fi elds.
The following class contains a static method. Examine the code and see if it compiles
and what its output is when
incrementCounter
is invoked:
1. public class StaticProblem {
2. public static int counter = 0;
3. public String message;
4.
5. public static void incrementCounter() {
6. counter++;
7. System.out.println(message + counter);
8. }
9. }
There is a problem with this class. Keep in mind that
incrementCounter
can be invoked
with or without any instances of
StaticProblem
. Let's assume there are no instances of
StaticProblem
in memory when
incrementCounter
is invoked. That means there are no
message
references in memory, so displaying
message
on line 7 does not make any sense.
Suppose we have 10 instances in memory. Then we would have 10 different
message
references in memory, and it is totally unclear which
message
we are attempting to display.
The
StaticProblem
class generates a compiler error on line 7. A static method does not
have access to the nonstatic fi elds in a class because a static method does not have a
this
reference. Remember, accessing a fi eld in a class implicitly uses the
this
reference if you do
not explicitly denote it. Line 7 actually looks like:
7. System.out.println(this.message + counter);
Because a static method does not have an object associated with it, using the
this
reference does not make sense and causes the following compiler error:
StaticProblem.java:7: non-static variable message cannot be
referenced from a static context
System.out.println(message + counter);
^
Search WWH ::
Custom Search