aspose file tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Static methods Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Static methods" Watch "Static methods" New topic
Author

Static methods

Vidyavathi saravanan
Ranch Hand

Joined: Sep 24, 2004
Posts: 34

Answer is d:

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 ]
Joe Borderi
Ranch Hand

Joined: Oct 23, 2004
Posts: 151
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).
Manikandan Jayaraman
Ranch Hand

Joined: Sep 15, 2004
Posts: 225
Hi Vidyavathi!

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!


Regards,<br />Mani<br />SCJP 1.4 (95%)<br />SCWCD 1.4 (94%)
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Static methods
 
Similar Threads
Dan's Mock FLow Question
Increment
can you explain this code.....
// simple Question
Method Arguments