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?
This means "this" object but there isn't one. In your case you can use the class name as @tibtof suggests.
To make your code work write it like this:
You can set static fields in static methods, but you don't have access to
this
in static method becausethis
represents the current instance of the object, and in a static method you have no instance.when we declare variable and method is static then this is share by among object where this keyword only pointing to current object. suppose you have created five object of class foo then only one copy of made of (int y) shred by all object.so if you access int y using this keyword then compiler get a ambiguity which object have to point because static int y is shared by all object . you have access static variable using class name.
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.
Keyword "this" refers to the object that you are operation with. In your case this inside any non-static methods or constructor (if you have one and and if you use "this" inside that), then "this" refers to that particular instance of the class Sub.So it is applicable only when the object is created. But anything in the static context of a class, you can use without even creating object for that as it is resolved during the class loading. "this" resolved only when object is created ( you can even say dynamically for which object). So "this" make sense in static context. Hope it helps. God bless.
I agree with all other people who replied before me. Let me try it in different way to answer this:
I guess, instance method/non-static method belongs to instance of a class (meaning sooner or later we need object ref to access it) so this keyword make sense inside instance block or method. But static keyword to any member of a class is interpreted as direct asset to class which a object if existed then has access to it. So in static context it's not sure that object is existing somewhere. That's why using this inside static area is not allowed in java.