public class Class1{
static int x = 5;
public static void fmethod(){
this.x;
}
}
- Compiled error : non-static variable this cannot be referenced from a static context this.x
public class Class1{
static int x = 5;
public static void fmethod(){
this.x;
}
}
- Compiled error : non-static variable this cannot be referenced from a static context this.x
1 Answer
Reset to default 1By using the this keyword we are accessing an attribute of an current object.
A field defined as static does not belong to a specific object, but to a class, and to access it you can use the following construction:
Class1.x
An alternative solution would be to define the field and the method as non-static and access it using the proposed construct:
this.x
this
in astatic
context. use the variable namex
directly (it will be accessible since it is declared in the same context) or useClass1.x
– mr mcwolf Commented Feb 6 at 8:15this
is a reference (pointer) to the specific instance of a class. Thereforethis
can only be used in specific instances. When you removestatic
from the declaration ofx
you make the variable accessible in a specific instance as well (likethis
). But since you are not creating an instance ofClass1
to access it through, you get an error. The same applies to methods declared withstatic
and those without. – mr mcwolf Commented Feb 6 at 9:33static
. – mr mcwolf Commented Feb 6 at 9:36