0

I am new to Java. I know static is class level and this is object level but please let me know if a static method can refer to the this pointer in java?

David
  • 3,787
  • 2
  • 29
  • 43
  • 2
    Since what you ask doesn't make sense, I have to ask what it is you are trying to do. The whole point of a `static` method is that it doesn't have a `this`, so the simplest way to change a static method to have a `this` is to remove the `static` keyword. – Peter Lawrey Sep 08 '13 at 16:30
  • This question addresses the use of static and what it does. It might be useful to you: http://stackoverflow.com/questions/413898/what-does-the-static-keyword-do-in-a-class – Jeremy Johnson Sep 08 '13 at 16:47
  • You can put an inner class inside a static method and inside that inner class, the `this` pointer would make sense. – emory Sep 09 '13 at 01:48

3 Answers3

4

No it does not make sense to refer this in static methods/blocks. Static methods can be called without creating an instance hence this cannot be used to refer instance fields.

If you try to put this in a static method, compiler will throw an error saying

cannot use this in static context

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
1

No, this cannot be accessed in a static context. June Ahsan said everything that you probably need to know but I would like to add a little background.

The only difference between an object method and a static method on byte code level is an extra first parameter for object methods. This parameter can be accessed through this. Since this parameter is missing for static methods, there is no this.

Example:

class MyClass {

    private int b;

    public void myMethod(int a){
        System.out.println(this.b + a);
    }

    public static void myStaticMethod(int a){
        System.out.println(a*a); // no access to b
    }
}

on byte code level becomes (roughly speaking, because byte code does not look like this)

class MyClass {
    int b;
}

void myMethod(MyClass this, int a){
    System.out.println(this.b + a);
}

static void myStaticMethod(int a){
    System.out.println(a*a); // no access to b
}
Sebastian
  • 5,177
  • 4
  • 30
  • 47
0

No but you can create a static object of you class in your class like this private static ClassName instance; and then you can set it with instance = this; in the constructor. this will then be available for you to use in a static method.

JWqvist
  • 717
  • 6
  • 15