Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a name for "this" in Java?

Eclipse will give an error, "The left-hand side of an assignment must be a variable", when I try something like:

public class Thing{    String a1;   int a2;    public void meth(){     Thing A = new Thing();     this = A;   } } 

I had to assign each variable (this.a1 = A.a1; this.a2 = A.a2;) as a work around.

Are there other ways to do this without going through each variable field?
And if this is not a variable what is it called?

like image 569
Jay Avatar asked Dec 12 '12 20:12

Jay


People also ask

What is this symbol called in Java?

The @ symbol denotes a Java Annotation. What a Java annotation does, is that it adds a special attribute to the variable, method, class, interface, or other language elements.

Can we use this () in a method?

The "this" keyword in Java is used as a reference to the current object, within an instance method or a constructor. Yes, you can call methods using it.

Is this keyword necessary in Java?

The call “this ()' is used to call more than one constructor from the same class. Q #2) Is this keyword necessary in Java? Answer: It is necessary especially when you need to pass the current object from one method to another, or between the constructors or simply use the current object for other operations.


2 Answers

this is a pseudo-variable that points to the current instance of the object, it can not be reassigned. It's also considered a keyword in the language, according to section §3.9 of the Java Language Specification.

like image 140
Óscar López Avatar answered Sep 20 '22 05:09

Óscar López


No, there is no easy shortcut.

And if "this" is not a variable what is it called?

this is not a variable, it's a keyword.

Even though this is special, in many respects it acts like a reference. Therefore, for consistency, this = A would have to be a reference assignment, which doesn't quite make sense.

You seem to be expecting this = A to perform a field-by-field copy from A to this, and indeed Java's designers could choose do that in this case. However, this would be inconsistent with other reference assignments, and the overall benefits of having this as an exception are not at all clear.

like image 34
NPE Avatar answered Sep 23 '22 05:09

NPE