My question is how come the increment statements in static main is able to access the non-static instance variable a. Wont' this generates a compiler-error?
(tag fixed and reformatted)
[ November 14, 2004: Message edited by: Barry Gaunt ] [ November 14, 2004: Message edited by: Barry Gaunt ]
Joined: Oct 23, 2004
The static main() method is not accessing the instance variables.
The static main() method is creating two local instances of the Red Class and holding them in two local references to Red, r1 and r2. These references are accessing their own instance variable (public int a) and the class variable (public static int b).
Joined: Sep 15, 2004
Dont take it as a rule of thumb, that static methods cannot access non-static variables. You have to first of all know, why is such a statement told!
When you take a static variable, it is common for all objects of the class and so gets initialised without even creating an object of the class. Similarly a static method can be called without creating a object of that class.
Now say, no object is created and a static method is invoked, on a class name. The static method SHOULD NOT BE ALLOWED TO ACCESS NON-STATIC MEMBER VARIABLES, because these variables will get initialised only when a object of the class is created. Currently they are not allocated any memory as no objects of the class are created. That is why the restriction is posed.
Now in the example given by you, we access non-static variables in a static main method through an object reference, which is valid thus!