Why cant we use non static data members within a static method?
- I can't understand your question. outside a static method within a static methodSarfraz– Sarfraz2010-07-31 13:50:20 +00:00Commented Jul 31, 2010 at 13:50
- presumably: why can't we use, within a static method, non-static data members declared outside that method.Yellowfog– Yellowfog2010-07-31 13:56:17 +00:00Commented Jul 31, 2010 at 13:56
3 Answers
Non static members belong to an object. A static method has no object.
If we have
class MyClass { int member; . . . public static int statFunc() { . . . foo = member; . . . } . . . }
If we have two instances of MyClass one where member = 1 and another where member = 2 and we call statFunc then statFunc has no idea which value of member to use.
Comments
Non-static data types refer to the instance of a class, the values of these variables can vary over each instance one creates from the class.
For example look at the following code:
public class name { String name; } Each name object can have a different name.
This is why non-static variables can only be accessed by non-static methods, otherwise a static method would never know which instance variable is ment.
I hope this helps.