Why can't we use 'this' keyword in a static method

Pradeep Vairamani picture Pradeep Vairamani · Jul 26, 2012 · Viewed 74.2k times · Source
class Sub {
    static int y;
    public static void foo() {
         this.y = 10;
    }
}

I understand that this represents the object invoking the method and that static methods are not bound to any object. But in the above mentioned case, the variable y is also static.

If we can invoke static method on class object, why can't we allow static methods to set the static variables of the class.

What is the purpose of this additional constraint?

Answer

brimborium picture brimborium · Jul 26, 2012

Because this refers to the object instance. There is no object instance in a call of a static method. But of course you can access your static field (only the static ones!). Just use

class Sub {
    static int y;
    public static void foo() {
         y = 10;
    }
}

If you want to make sure you get the static field y and not some local variable with the same name, use the class name to specify:

class Sub {
    static int y;
    public static void foo(int y) {
         Sub.y = y;
    }
}