-2

I have a question about this fragment of code :

public class Inner {

static int a;

    public static void main(String[] args) {
        a = 0;
    }

    public static void g() {
        this.a = 0;
    }
}

`

Why we can't use "this.a" in static method, but we can use "a" without "this"?

Photo of compilation error: https://www.dropbox.com/s/5q6y3ldsf37p0h3/%D0%97%D0%BD%D1%96%D0%BC%D0%BE%D0%BA%20%D0%B5%D0%BA%D1%80%D0%B0%D0%BD%D0%B0%202017-05-27%2017.28.34.png?dl=0

  • 1
    read this [Why can't we use 'this' keyword in a static method](https://stackoverflow.com/questions/11664522/why-cant-we-use-this-keyword-in-a-static-method) – Youcef LAIDANI May 27 '17 at 14:40

1 Answers1

1

Because this points to an instance of the class, in the static method you don't have an instance.

The this keyword refers to the current instance of the class. Static member functions do not have a this pointer

You'll notice the definition of a static member is

Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object

Which is why this has nothing to point to.

ruithebear
  • 71
  • 5