Reputation: 801
I figured out how to have an object pass itself to another and have a field in it updated. I did so by having ObjectA pass itself to ObjectB. Then ObjectB changes a field in ObjectA. Starting in Main Method: (and leaving out method headers and such)
ObjA.changeField(Obj2)
In ObjectA
Obj2.callChangeMethod(this);
In ObjectB
Obj1.makeChange();
What I'm confused about is why did I have to pass "this" in line2 versus passing ObjA?
Thanks
Upvotes: 0
Views: 1504
Reputation: 425198
The only reference an object has to itself is the this
keyword. Ultimately, there is no other way for an object to refer to itself.
Upvotes: 0
Reputation: 19349
The reason is quite simple actually: it all has to do with the scope of the variables.
Here is a slightly embellished version of the code you presented:
public static void main(String[] args) {
ObjectA Obj1 = new ObjectA();
ObjectB Obj2 = new ObjectB();
Obj1.changeField(Obj2);
}
The thing to notice about this code is that Obj1
and Obj2
are declared inside of the main
method. This means that they belong to the main method, and cannot be used outside of main
. This is what the "scope" means. If a variable is declared inside a class, only that class has access to it. If declared in a method, only that method can use it. The same holds for loop structures, and any other kind of block you can imagine. Essentially, if the variable was declared inside a pair of {}
, then it belongs to that pair of {}
.
So now if you look at your ObjectA
class, you'll notice that it sits all by itself - it wasn't declared as part of the main
method, so it can't use the variable Obj1
- the ObjectA
code has no idea that Obj1
even exists.
That is why you must use the this
keyword. You don't have access to Obj1
, so you need to use a "variable" that you do have access to - in this case, you have this
which always refers to the current instance of the class.
So although you are still using the same object (the one created by new ObjectA()
), you simply have different variables which refer to that object, depending on which code you are currently looking at. The scoping rules do get a little more complex, but the more you play around with Java, and the more you understand classes vs instances vs references to instances, the easier it becomes to use them comfortably.
Upvotes: 1