Java: Why ‘this’ keyword cannot be used in static methods?
Firstly, let’s understand the difference between ‘this’ and ‘static’ keywords.
What is ‘this’ ?
‘this’ keyword in Java refers to the current object of a method or a constructor that have same names. ‘this’ is required only when you need to differentiate between an instance variable and local variable/method parameters.
Syntax:
this.instance_variable_name=method_variable_name;
When is ‘this’ used?
What is ‘static’?
The static keyword in Java is used to share the same variable or method of a given class.
Methods declared as static have several restrictions:
- A class variable is defined using the keyword static. It belongs to a class, not to individual objects of the class.
- Can directly call the method/variable using the class name i.e. without creating an instance.
- They cannot refer to this or super in any way.
Why can’t we use ‘this’ and ‘static’ together?
‘this’ keyword is only applicable where an instance of an object is created. Static method has no instance created because static method belongs to the class.
What will happen if we use it together?
If you still try to do so, a compile time error is generated.
error: non-static variable this cannot be referenced from a static context.
Any alternatives?
If you want to make sure you get the static field and not some local variable with the same name, use the class name to access it:
Syntax for accessing static methods: className.methodName();
Syntax for accessing static variables: className.variableName();
class Example{
static int a;
public static void foo(int a) {
Example.a = a;
}
}
Happy Learning! :)