
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Use 'this' Keyword in Static Context in Java
A static method or, block belongs to the class and these will be loaded into the memory along with the class. You can invoke static methods without creating an object. (using the class name as reference).
Whereas "this" in Java acts as a reference to the current object. But static contexts(methods and blocks) doesn't have any instance they belong to the class.
In a simple sense, to use “this” the method should be invoked by an object, which is not always necessary with static methods.
Therefore, you cannot use this keyword from a static method.
Example
In the following Java program, the class ThisExample contains a private variable name with setter and getter methods and an instance method display(). From the main method (which is static) we are trying to invoke the display() method using "this".
public class ThisExample { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public void display() { System.out.println("name: "+this.getName()); } public static void main(String args[]) { this.display(); } }
On compiling, this program gives you an error as shown below −
Compile time error
ThisExample.java:17: error: non-static variable this cannot be referenced from a static context this.display(); ^ 1 error