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?
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; } }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With