Why can’t we use ‘this’ keyword in a static method

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;
    }
}

Leave a Comment