class Foo { int x = 3; public static void main(String[] args) { system.out.println("x is " + x); } }
Understand that this code will never compile, because you can't access a nonstatic (instance) variable from a static method. Just think of the compiler saying, "Hey, I have no idea which Foo object's x variable you're trying to print!". Remember, it's the class running the main() method, not an instance of the class.
Of course, the tricky part for the exam is that the question won't look as obvious as the preceding code. The problem you're being tested for accessing a nonstatic variable from a static method will be buried in code that might appear to be testing something else. For example, the preceding code would be more likely to appear as
class Foo { int x = 3; float y = 4.3f; public static void main(String[] args) { for (int z - x; z < ++x; z--, y = y + z) { // complicated looping and branching code } } }So, while you're trying to follow the logic, the real issue is that x and y can't be used within main(), because x and y are instance, not static, variables! The same applies for accessing nonstatic methods from a static method. The rule is, a static method of a class can't access a nonstatic (instance) method or variable of its own class.
Refrence: SCJP Sun® Certified Programmer for Java™ 6 Study Guide Exam (310-065)
No comments:
Post a Comment