Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 246
Pradeep Vairamani Avatar asked Jul 26 '12 07:07

Pradeep Vairamani


2 Answers

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;     } } 
like image 57
brimborium Avatar answered Sep 28 '22 03:09

brimborium


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.

like image 40
Sachindra N. Pandey Avatar answered Sep 28 '22 02:09

Sachindra N. Pandey