Skip to main content
gamedev.net
🔒 Locked

[java] static method access

Started by Fooshnucka 2 replies 150+ views
Original Post
Fooshnucka
Fooshnucka
are variables declared in a classes main method accessible by static methods belonging to the same class?
bslayerw
bslayerw
Try it and see what happens. It''s take you 2 minutes to create a dummy class and test it.
snowmoon
snowmoon
Variables created in the main finction will NOT be accessable outside of that scope. You will need to declare the vars class static and then access them from main and your other static methods.
nonnus29
nonnus29
I know exactly where your coming from fooshnucka. when I started programming java I tried to put all my methods and variables in the class definition before the main method and guess what? it doesn''t work because as you know main is static.

In java a static method or variable in a class will exist wether there is an object of the class created or not. So if you try to access a static from nonstatic it might not be there so obviously you can''t do this.

So whats the point? The example that i''ve seen that makes the most sense to me is suppose you have a class Sphere and you want to create a bunch of spheres and you want to keep track of how many sheres you have. You could include a variable count=0; and a method increment (); to keep track of how many you have. But what if you want to know if you have zero? You can''t access count cause there are no spheres. Make count static so it will exist even if there are no objects of type sphere and you can tell if there are zero.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.