1

I came across this particular behavior while working but I am not really sure what is the issue here. As per me Static keyWord has some feature as

1. Belongs to class rather than object.

2. Static method can access static instance variable of the class.

But can some one please expain the particular behavior:

      public static final int x=12;
      public static  void go(final int x){
          System.out.println(this.x);
      }

while writing this particular line I am getting complile time error at printing statement "this.x" in Eclipse as "can't use this in static conetext".

Can some one explain what is missing in my understanding??

vinod bazari
  • 210
  • 1
  • 2
  • 10

2 Answers2

2

You can't specify that you want the class level x with this. You need the class name. Like,

class Example {
  public static final int x=12;
  public static  void go(final int x){
    System.out.println(Example.x);
  }
}

You could also use a different variable name for the method parameter.

public static final int x=12;
public static void go(final int y){
  System.out.println(x);
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

"this" refer to current object and not to class.

It should be like

public static final int x=12;
      public static  void go(final int x){
          System.out.println(ClassName.x);
      }
Krutik Jayswal
  • 3,165
  • 1
  • 15
  • 38