0

Why cant we use non static data members within a static method?

2
  • I can't understand your question. outside a static method within a static method Commented Jul 31, 2010 at 13:50
  • presumably: why can't we use, within a static method, non-static data members declared outside that method. Commented Jul 31, 2010 at 13:56

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

-1

Because it doesn't make any sense. Instance variables are associated with an instance of the class. Static methods aren't. Which instance's variables would you be talking about within the static method?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.