Why can't we use 'this' keyword in a static method
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?
Solution 1:
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;
}
}
Solution 2:
The main reason why we can not use "this" in static method context:-
this :- "this" means current class OBJECT , so its clear that "this" only come in the picture once we intended to create an Object of that class.
static method:- there is no need to create an object in order to use static method. means "instance" or object creation doesn't any sense with "static" as per Java rule.
So There would be contradiction,if we use both together(static and this) . That is the reason we can not use "this" in static method.
Solution 3:
this
is referring to this instance of the object Sub
. As the method is static
, there is not an instance of Sub
.
Solution 4:
To make your code work write it like this:
class Sub {
static int y;
public static void foo() {
Sub.y = 10;
}
}
You can set static fields in static methods, but you don't have access to this
in static method because this
represents the current instance of the object, and in a static method you have no instance.