Can we use "this" keyword in a static method in java?


The static methods belong to the class and they will be loaded into the memory along with the class. You can invoke them without creating an object. (using the class name as reference).

Example

public class Sample{
   static int num = 50;
   public static void demo(){
      System.out.println("Contents of the static method");
   }
   public static void main(String args[]){
      Sample.demo();
   }
}

Output

Contents of the static method

The "this" keyword is used as a reference to an instance. Since the static methods doesn’t have (belong to) any instance you cannot use the "this" reference within a static method. If you still, try to do so a compile time error is generated.

Example

public class Sample{
   static int num = 50;
   public static void demo(){
      System.out.println("Contents of the static method"+this.num);
   }
   public static void main(String args[]){
      Sample.demo();
   }
}

Compile time error

Sample.java:4: error: non-static variable this cannot be referenced from a static context
   System.out.println("Contents of the static method"+this.num);
                                                      ^
1 error

Updated on: 05-Aug-2019

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements