I have used Java for about six months but I am somewhat at a loss as to exactly how the this
statement works. I know that it is used to refer to an calling instance. But why does it not need to be used in the main method to reference the object that is created in the main method?
I think that the this is always referring to the current object that has priority over the other objects. In the constructor the this is for the new object being created, correct. In the main method the this.x.method is referring to the object that is in the main statement.
Question: The this keyword refers to the current object that is being created? or does it refer to the object that is being made into a new object?
class:
public class DDHThisTest {
public int x = 0;
public int y = 0;
public DDHThisTest(int a, int b) {
this.x = a;
this.y = b;
}
public static void main(String[] args) {
DDHThisTest i = new DDHThisTest();
this.i.x = 10;
}
}
Error:
Cannot use this in a static context