I looked at a Why can't I use the keyword "this" when referring to fields in static methods?
and thought that accessing static members through a reference variable is ok, but using this
to access such members is not okay. Look at the code below.
static int month;
public static void setMonth(int x)
{
Date date = new Date();
date.month = x; //fine, why ?
this.month = x; //compiler error, why ?
}
It clearly shows that this
is not the same as a reference variable. If that is so, then what is it really? I need to understand the true meaning of this
to understand why it cannot be accessed from a static context.
Please don't give me links to random blogs or oracle tutorials which say that this
can't be used from a static context - I already know that. I want to look beyond that and understand why it can't be used.
Code in linked question -
public class Date
{
static int month;
public static void setMonth(int x)
{
this.month = x; //compiler error
}
public static int getMonth()
{
return month; //compiles just fine, no error
}
}