jnardiello
jnardiello

Reputation: 699

this as reference in Object assignment

I know that this question could look a bit trivial with an obvious answer, but i could't find any explanation around, nor on StackOverflow nor on Google.

The following code:

Object o = this;

Can it be used inside a Class method (an instance method belonging to a generic Class, not a Static method) which needs to manipulate (let's say with a for-loop) Object o updating its reference during each iteration?

Again, consider the following code assuming we have an Array MyObject[] oArr and otherMethod is available to MyObject:

MyObject obj = this;
for(MyObject f : oArr){
    obj = obj.otherMethod(f);
}

What is happening here is:

To be completely honest what is confusing me here is this line of code:

MyObject obj = this;

It's the first time ever that i find this without a variable/method name, used to simply reference an object.

Did i get right what is going on here? Am i missing anything? Do you have a link where i can find additional info about similar uses of this?
Thanks

Upvotes: 0

Views: 88

Answers (3)

Onur A.
Onur A.

Reputation: 3017

MyObject obj = this;

this also can be used to point to constructors, so in here this is used to refernce to class which this line is in the context of, but the refernced class should be same type / have a inheritance relatinship in order to refernce, to be clear assume you write this line in AClass

class AClass {
  MyObject obj= this; // in here you refer the AClass by calling this,
}

Upvotes: 0

Bohemian
Bohemian

Reputation: 425188

There is nothing "wrong" about assigning this to a variable.

In your case, doing so sets up the initial conditions for your iterative code.

A reasonable such usage may be in a linked list, where the root node is this:

// find end node, to add another node perhaps
Node node = this;
while (node.next != null)
    node = node.next;

Upvotes: 3

Aniket Inge
Aniket Inge

Reputation: 25725

you cannot access this in a class(static) method, because this simply does not exist in the context of static methods.

AFTER EDIT:

However, this is an object of the current class in context. So, it is OK to assign it to another variable.

Upvotes: 2

Related Questions