28

Can you please help me with below code. The error is: "Cannot use This in a static context"

public class Sample2 {
    /**
     * @param args
     */
    public static void main(String[] args) 
    {
        Sample2 sam=new Sample2();  

        //Below code works fine
        System.out.println(sam);

        //Below code is displaying error
        System.out.println(this);
    }
}
webmaster777
  • 1,442
  • 2
  • 12
  • 17
Cyborgz
  • 641
  • 1
  • 9
  • 18
  • 1
    possible duplicate of [non-static variable cannot be referenced from a static context](http://stackoverflow.com/questions/2559527/non-static-variable-cannot-be-referenced-from-a-static-context) – Brian Roach May 01 '13 at 09:13
  • possible duplicate of [why can't we use this keyword in a static method](http://stackoverflow.com/questions/11664522/why-cant-we-use-this-keyword-in-a-static-method) – fglez May 07 '13 at 09:37

5 Answers5

40

See, "this" keyword refers to current object due to which method is under exceution. As, you cannot call static method using instance of class. That is why, "this" can't be used in the above example in a static method as it is trying to print current instance wich is not at all created. So, I think thats why there is an compile time error that you are getting.

  • 3
    Actually. you can call a static method by using an object of the class in which the static method has been declared. Compiler will give no error. We do not do this because its a very bad way of calling/using a static method. :) – Kaveesh Kanwal Feb 18 '15 at 15:41
18

They keyword this refers to the instance of the class. In a static context, you have no instance, therefore you can't refer it.

For more information, refer to this answer: What is the meaning of "this" in Java?

Community
  • 1
  • 1
Matten
  • 17,365
  • 2
  • 42
  • 64
  • oh okay. I assumed that object reference of 'sam' would be available in 'this'. from the below answer, its clear that "this" keyword refers to current object due to which method is under execution" – Cyborgz May 02 '13 at 05:31
3

In java you can not use this in static methods (static context).

Static methods do not point to any instance of the enclosing class.

A static method cannot refer to “this” or “super” keywords in anyway

Refer official docs on this keyword

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
2

If we try to access this from a static context , compiler has no way to guess which instance, you are referring too. main is a static method here.

Vivek Vermani
  • 1,934
  • 18
  • 45
0

writing this means in static context we are expecting to return the address of the object. Though its totally legal to have an object calling static methods but it is not an obligation. So compiler stops possibility of any error in case object is not created for the class.

Jain
  • 201
  • 2
  • 2