-1

It seems like its using local variable of the method!!!! I thought it would give an error on call non static variable on static method but it did not.

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

Actually it doesn't have a error which is interesting..

19mddil
  • 53
  • 8
  • 5
    The instance variable `x` doesn't exist at all within the context of your `go` method because the method is static. The only `x` it can see is the parameter. – JonK Jun 05 '19 at 15:31
  • You need to learn what static means. The non static field `x` belongs to instances of your class. It makes no sense to access it outside of an instance. Its like saying `name` for a Person class when u created 100 person instances, whos name? `john.name` or `jane.name` etc. And in your static method you are not inside any instance, static methods belong to the class. So a non static `x` field is only known inside instances of your `foo` class, created by `new`. – Zabuzard Jun 05 '19 at 15:34

1 Answers1

6
System.out.println(x)

will print the parameter of the method go

If you want to access field of the class, use this keyworld (if your method not static):

System.out.println(this.x)

In your case, you need to have an instance of foo class and use

foo f = new foo();
System.out.println(f.x);
Limmy
  • 697
  • 1
  • 13
  • 24