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;
    }
}
m.cekiera
  • 5,365
  • 5
  • 21
  • 35
Pokemon
  • 461
  • 5
  • 8
  • 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. – Philippe Paré Sep 14 '15 at 19:38
  • 4
    possible duplicate of [Why static classes cannot have nonstatic methods and variables](http://stackoverflow.com/questions/7783828/why-static-classes-cannot-have-nonstatic-methods-and-variables) – Ehsan Sajjad Sep 14 '15 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. – HABO Sep 14 '15 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](https://en.wikipedia.org/wiki/Singleton_pattern) instead of creating a static class. – Bob Kaufman Sep 14 '15 at 19:50

1 Answers1

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.

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109