1

Why we cannot use instance variable in a static method? I know that static methods are called without creating instance of classes but what restricts the non static variable to be used in static method?

class MyClass
{
    // non-static instance member variable
    private int a;
    //static member variable
    private static int b;

    //static method
    public static void DoSomething()
    {
        //this will result in compilation error as “a” has no memory
        a = a + 1;
        //this works fine since “b” is static
        b = b + 1;
    }
}
4
  • 4
    You need an instance of your class in order to access an Instance Field. static fields are accessible by instance and static methods, but not the other way around. Commented Sep 14, 2015 at 19:38
  • 4
    possible duplicate of Why static classes cannot have nonstatic methods and variables Commented Sep 14, 2015 at 19:39
  • 2
    Since there is an a in each instance, which would you expect to be incremented? What if you haven't created any instances yet? You could pass an instance to a static method as a parameter. Commented Sep 14, 2015 at 19:40
  • 1
    To @HABO's point: are you expecting to instantiate only one object of type MyClass? If so, consider the infinitely abusable Singleton Pattern instead of creating a static class. Commented Sep 14, 2015 at 19:50

1 Answer 1

6

Trying to put a non-static variable inside a static method makes the compiler wonder which instance of this variable should I really be updating? The static methods are not related to a class instance, so it will be impossible to call an instance variable on an instance when no instance exists.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.