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".

 Live Demo

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

Updated on: 30-Jul-2019

893 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements