The key to a static method, or variable more specifically, is the fact that it isn't tied to any one instance of a class. That's the whole point of a static variable, no matter how many instaces of a given class you have, they all point to the same memory location that stores the value of the static variable. Static methods, of course, work on these static variables.
BUT, with inner classes, the inner class is associated with a given outer instance. So, if you have ten outer instances, should you have ten, different, static memory locations, for each of the inner instances they contain, or one static memory location for each instance? The questions really doesn't have an answer, because either way, the answer is unsatisfactory. Furthermore, when a static method is called, which static variable does it use, especially if there are many outer instances?
This is the crux, or paradox, or problem with inner classes having static variables or methods.
-Cameron McKenzie
Which of the following lines of code must be commented out in order for the code below to compile:
public class TestClass {
public class InnerClass {
static int x=5; //line a
static final int y=10; //line b
public static void testStaticInner() {} //line c
public static final void testStaticFinalInner() {} //line d
}
}
� a) //line a
� b) //line b
� c) //line c
� d) //line d
Options a) c) and d) are correct, becauase they are incorrect lines of Java code.
This nested class is not static, and the rule is, non-static nested classes cannot define any static member variables or methods, with the exception of a static final variable, which is better thought of as a constant in Java, as opposed to an actual static member.
An attempt to compile the code above would generate compiler error messages along the lines of: inner classes cannot have static declarations
Which line of code will trigger a compile error?
public static class TestClass { //line a
public static class InnerClass {
static int x=5; //line b
static final int y=10; //line c
public static void testStaticInner() {} //line d
}
}
a) //line a
b) //line b
c) //line c
d) //line d
Option a) is correct.
Top level classes cannot be declared as being static. However, an nested class can indeed be declared as being static.
A static nested class can declare both instance variables and methods, and static variables and methods, so lines b) c) and d) would not cause compile errors.
Taking the
word static out of the top level class declaration would allow this code to compile.
[ June 26, 2007: Message edited by: Cameron W. McKenzie ]