Reputation: 3213
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
Upvotes: 0
Views: 2278
Reputation: 136
main method is a static method.
keyword this
is to be used in object/instance scope not in a static block.
Simply replace this.i.x = 10;
with i.x = 10;
and you should be fine.
Upvotes: 3
Reputation: 21
Main is a static method and it is called before the object of DDHThisTest class is made. So ypu are trying ro refer to an instance of a class which is yet to be instantiated. So you are getting the error. In other words you know that only static variables can be accessed from static methods. But 'this' is an instance variable so to say; because of which you can't access it from static method.
Upvotes: 2
Reputation: 70899
When you are in a static
block, you have no object scope. That means that there is not a particular instance of the class you are working with, so there is no reference to "this instance of the class".
Upvotes: 2
Reputation: 34146
You cannot use this.i.x
since you cannot refer to instance variables inside a static
method, in this case main()
. To solve this just remove the this
before i.x
.
public static void main(String[] args)
{
DDHThisTest i = new DDHThisTest(1, 2);
i.x = 10;
}
Note: Don't forget to pass arguments to the constructor while creating an instance of DDHThisTest
, because you have not declared a constructor without parameters.
Upvotes: 3
Reputation: 11
The keyword "this" is reserved to be used as part of an instance. If you remove the "this.", you should be fine.
Upvotes: 1