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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With