There only one count variable since static
Applying Access Modifiers 183
One more time because this is really important: what does the following output?
The following is a common mistake for rookie programmers to make:
public class Static {
private String name = "Static class";
public static void first() { }
public static void second() { }
public void third() { System.out.println(name); } public static void main(String args[]) {
first();
second();
third(); // DOES NOT COMPILE
} }
TA B L E 4 . 3 Static vs. instance calls
|
Legal? | ||
---|---|---|---|
Yes |
|
||
|
No | ||
|
Yes | ||
A static method or variable | |||
|
Another instance method | Yes | |
Using a reference variable | |||
Lines 3 and 4 are fi ne because both static and instance methods can refer to a static variable. Lines 5–8 are fi ne because an instance method can call a static method. Line 11 doesn’t compile because a static method cannot call an instance method. Similarly, line 14 doesn’t compile because a static variable is trying to use an instance variable.
A common use for static variables is counting the number of instances: