- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Is it possible to 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
- Related Articles
- Can we use "this" keyword in a static method in java?
- Is it possible to create static constructor in java?
- static Keyword in Java
- Is it possible to assign a reference to "this" in java?
- static Keyword in Java programming
- Java static keyword
- Can a "this" keyword be used to refer to static members in Java?\n
- Does static factory method internally use new keyword to create object in java?
- Is it possible to use $(this) and universal selector (*) with jQuery?
- What are the 6 ways to use this keyword in Java?
- static keyword in C++ vs Java
- This keyword in Java
- Is it possible to share a Cuda context between applications
- Why can't we use the "super" keyword is in a static method in java?
- What is the use of this keyword in TypeScript?
