27

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?

eckes
  • 10,103
  • 1
  • 59
  • 71
Jay
  • 396
  • 3
  • 6
  • 40
    Don't just down vote, explain why this doesn't make sense. – Oliver Dec 12 '12 at 20:40
  • 1
    http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html – Brian Roach Dec 12 '12 at 20:41
  • 8
    The name for 'this' is 'this'. Not a real question. – user207421 Dec 12 '12 at 20:42
  • 8
    Why are people upvoting "I didn't do any research at all" ? – Brian Roach Dec 12 '12 at 20:42
  • From your assignment block, the use of `this` is meaningless. There's no ambiguity in the variables you're assigning. – Makoto Dec 12 '12 at 20:42
  • 1
    @EJP then you need to read more than just the title. The title itself, admittably, is incorrect. – John Dvorak Dec 12 '12 at 20:44
  • 2
    @JanDvorak The question in the title is not a real question. The title is not only incorrect, it is also both meaningless and irrelevant. The imputation that I haven't read further is false. – user207421 Dec 12 '12 at 20:45
  • 21
    @BrianRoach if the guy doesn't understand OOP enough to know why the question doesn't make sense, he could probably use an explanation of what `this` means rather than just downvote, downvote, close. We were all beginners once... – Oliver Dec 12 '12 at 20:45
  • 4
    @Oliver - Which is why I linked to the excellent tutorial provided by Oracle on the subject which is at the top of the list if you google "java this tutorial". The number one reason to downvote is *no research effort*. I'm also out of votes from last night, so I don't have a dog in that race. – Brian Roach Dec 12 '12 at 20:46
  • 10
    @Oliver the point Brian makes is that the asker shows no research, not that he does not know the basics. – John Dvorak Dec 12 '12 at 20:46
  • 3
    @Oliver I am agree with you. So many people ask question are nubiee, but we should help them not discourage them. – Smit Dec 12 '12 at 20:47
  • Essentially what you're work around is trying to do is set your instance variables to null, based on what you've put in your code, as the new Thing has no instantiation of it's variables. I can't imagine what you're trying to accomplish here that would require a second instance of Thing. – MildWolfie Dec 12 '12 at 21:45
  • The only language I'm aware of that lets you reassign "this" is Objective-C (where the roughly identical concept is called "self"). C++ has object-to-object assignment, but that's not the same thing. The difference is that in Objective-C you're changing the pointer, while with C++ you're changing the object addressed by the pointer. – Hot Licks Dec 13 '12 at 01:35
  • 3
    The this tag also answers the second part of the question, amusingly. – Drazisil Dec 13 '12 at 04:01

12 Answers12

71

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.

Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • "Pseudovariable" is a very good term for it. It's in almost every object-oriented C-style language (C++, Java, C#) and has parallels in all the other O/O langs (VB "Me", Obj-C "self", Delphi "Self"), all of which have practically the same usage and restrictions. – KeithS Dec 13 '12 at 04:04
  • 7
    its not a "pseudo-variable", it is a `keyword` that is treated like an `expression` s/a (1 + 2). And (1 + 2) = A does not make sense. See my answer below – jermel Dec 13 '12 at 04:44
  • It is an immutable reference value. – Hot Licks Aug 30 '14 at 02:03
24

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.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • 1
    The explanation you give is plain wrong: Other languages allow such style of assignment just fine and either infer which field assignments are necessary or let the programmer provide this information. Java’s refusal to allow the assignment has got nothing to do with fields. I’m surprised by the number of upvotes this has garnered. – Konrad Rudolph Dec 12 '12 at 23:13
  • @KonradRudolph: Many other languages permit many other things. The question is specifically about Java, and Java's design is rather strict in many respects. This is one facet of that. – NPE Dec 13 '12 at 07:49
  • 1
    @NPE I am objecting specifically to this: “Only you, the programmer, know how the assignment should work” – regardless of language this is not a reason to forbid this assignment. This is true for Java as well, I just mentioned other languages because they *show* that this reason is wrong. The real reason is completely different (assignment on reference objects in Java assigns references, not values, and `this` cannot be assigned to). Your explanation is plausible, but simply wrong and doesn’t apply. – Konrad Rudolph Dec 13 '12 at 08:32
  • @KonradRudolph: You're reading it differently than what was intended. I'll see if I can improve the wording. – NPE Dec 13 '12 at 08:34
9

this refers to this instance of the class.

You cannot assign to this

Jakob Bowyer
  • 33,878
  • 8
  • 76
  • 91
9

this is a java reserved keyword which refers to the current object. its not a variable its a java reserved keyword. so this = A; is invalid. using this keyword we can refer to any instance variable or method of the current object. you have to refer to the instance variable like:

this.a1 = A.a1;

From Doc:

The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter.

PermGenError
  • 45,977
  • 8
  • 87
  • 106
6

You can't assign to this in Java. It's not a variable; it's a keyword.

One thing you might consider, if you don't need a particular instance, is just returning your new instance.

public class Thing{

  String a1;
  int a2;

  public Thing meth(){
    Thing A = new Thing();
    return A;
  }
}

and you'd use it like

whatever = whatever.meth();
cHao
  • 84,970
  • 20
  • 145
  • 172
  • You also can't assign to `final` variables outside of where it is initialized (for local variables) or the constructor (for instance variables) – newacct Dec 12 '12 at 23:58
  • "this" is a keyword, but it can be considered to be a variable as well - it "varies" based on the context (even if it is not variable [<- adjective] in the sense that it can be changed by the user). – simon Dec 19 '12 at 20:39
  • @simon: Someone else actually called it a "pseudo-variable", which seems almost fitting. I couldn't consider it a variable, though; a variable (even a `final` one) has a place where its value is stored, and as far as i can tell, there's really no such place for `this`. – cHao Dec 19 '12 at 21:02
  • In compiled bytecode, `this` is the first parameter of a method call (much like Python's `self`), so it really does have a location. In fact, it works very much like a final parameter. – C. K. Young Oct 17 '13 at 16:52
5

According to java lang spec §15.8.3 this is a keyword that is either an expression or statement

  1. When used as a primary expression this denotes a value that is a reference to the object for which the instance method was invoked.
    • Expression: Something which evaluates to a value. Example: x++
  2. The keyword this is also used in a special explicit constructor invocation statement
    • Statement: Syntactic elements that control the execution of a program, which are executed for their effect and do not have values Example: if (true)

In either case it is not a variable

  • Variable: A storage location with an associated type

In your case this is an expression and not a variable. But for all intents an purposes just call it a keyword

  • Keyword: A character sequence, formed from ASCII letters, are reserved for use ... that cannot be used as a variable name
jermel
  • 2,326
  • 21
  • 19
1

this refers to the owner of the method. In this case, the owner is the object itself.

Sometime, this may not refer to the class that you are writing code. Such as in the annoymous class. A common example is the anonymous listener.

 button.addActionListener(
        new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                this; // refers to the ActionListener
            }
        }
    );

In addition, you can return this can do method chaining. Supposed you have a class called Homework and it has a method addTask.

public Homework addTask(String task){
return this;
}

you can call the addTask method like

homework.addTask("a").addTask("b").addTask("c");
code4j
  • 4,208
  • 5
  • 34
  • 51
1

I think the OP is asking for the ability to assign the contents of one object to another, rather than to assign a new value to the "this" pointer. C++ has this ability -- you can override the assignment operator -- but Java has no such ability.

It would be a nice feature to have in some occasional cases, but it's simply not currently possible, and it doesn't really fit the Java "mold" to provide the function in the future.

The capability would be more useful (and there would be more motivation to provide it) if Java allowed objects to be embedded in other objects (vs simply embedding referenced), but that's not in the cards either.

Hot Licks
  • 47,103
  • 17
  • 93
  • 151
0

There is no1 way to copy the values of all fields from one instance onto another in the basic Java language. And you should typically not need it. You can most often just replace the reference to the new instance or work directly on the target instance.

In your case when you want to reset all fields of a object to the initial values (and there is seldomly a need for it) you typically use a reset method which eighter works on its own instance or is a static one working on any given object.

So

class A {
  String a1; int a2;
  void reset() { a1 = ""; a2 = 0; }
}

would be used as

A a = new A();
// modify a
a.reset();

and

class A {
  String a1; int a2;
  static void reset(A anotherA) { anotherA.a1 = ""; anotherA.a2 = 0; }
}

and use it like:

A.reset(a);

In both cases it makes sense to use the reset method also for setting the initial values in the constructor: A() { A.reset(this); } or A() { this.reset(); }

1 actually there are some libraries to do it, and you can code it with the help of reflection, the only reason I see it is used is to implement a clone() method or for some kind of wrapping/stubbing.

eckes
  • 10,103
  • 1
  • 59
  • 71
0

It sounds to me like what you're trying to do is have a method that reinitializes your object, i.e., set's it back to it's initial values. That's why you want to create a new object, and assign it to the current object, right?

If that's the case, let's try a different way of doing it, since, as has been said, you can't reassign this.

What if, instead of doing that, you tried something like this:

public class Thing {

    String a1;
    int a2;

    public Thing() {
        this.meth();
    }

    public void meth() {
        this.a1 = "a1";
        this.a2 = 2;
    }

}

This way, Thing.meth() actually initializes your object, and the constructor calls it when the object is created. Then you can call it again whenever you'd like.

Dan Jones
  • 1,337
  • 11
  • 22
0

==Disclaimer, I don't know java==

You would want to assign manually.

I'm not sure why you are trying to create a new instance of Thing inside Thing, but as you don't set the values of a1 and a2 you would need to assign them the way you did.

this is a reserved keyword pointing the class object it is inside.

For example, if you wanted to have another function named fish() your code may look something like this.

public class Thing{

  String a1;
  int a2;

  public Thing meth(){
    Thing A = new Thing();
    return A;
  }

  public Thing fish(){
    this.a1 = "foo";
    this.meth();
    return A;
  }
}
Drazisil
  • 3,070
  • 4
  • 33
  • 53
0

When you do this = stuff; you are trying to replace the current object instance reference (in this case, the one that you are initializing in the constructor) with another thing, and (in the particular case of java) thats illegal and the language forbids you of doing it.

Think about it, if you could replace the reference to your current instance just like that, then you could incur in some serious memory and security problems (the reference to the constructed object will be lost and overrided by some unknown object).

What is totally valid is referencing members of your current object using the . operator, because they are owned by this, so no problems should arise (at least not evident ones).

The JVM has some inner security measures (e.g., method max stack size verification, class file format validation, etc) that prevents from easy binary manipulation and are enforced by the language syntax. This could be seen as one of those.

higuaro
  • 15,730
  • 4
  • 36
  • 43