cloister
Full Member
Offline
Posts: 138
Re: xyz=new XYZ(this); // please explain (this)
Reply #3 - Mar 20th , 2009, 6:15pm
While that reference page is certainly correct, I'm not sure it answers your basic question. In object oriented programming (which Java supports), the keyword "this" is a special, magic variable that allows objects to refer to themselves. You don't often need to do this, which is why you don't actually encounter "this" very much in real code. But sometimes, you do. You definitely need it in cases where the name of a member variable of the class conflicts with some other variable elsewhere in the program, and you need to differentiate them. "this.whatever" will always be "the 'whatever' member variable of the current object". Sometimes it's just nice to have as a way of making the code clearer. Usually this situation comes up when you're initializing a new instance of a class from an existing object of that class: Particle copy(Particle parent) { Particle clone = new Particle(); clone.mass = this.mass; clone.velocity = this.velocity; return clone; } In those cases, using the "this" keyword, while optional, makes it explicitly clear, to anyone else who might be reading the code later, exactly what's going on. It's a form of self-documenting code. While the above code is totally legit, a lot of people will complain that it is bad object oriented style because really you should use a so-called "copy constructor" for that, one that takes an object of the class's own type as a parameter: class Particle { float mass; Vector3D velocity; Particle(Particle parent) // copy constructor { this.mass = parent.mass; this.velocity = new Vector3D(parent.velocity); // assuming Vector3D also has a copy constructor } // ... blah blah blah } This becomes handy, and makes for cleaner code, when you get into situations where an object needs to make one or more copies of itself. You might find something like this in a physics simulation where, when two asteroids (Particles) collide, they each break into pieces: // Split this particle into some number of others, with the // mass equally distributed among them. Particle[] split(int howMany) { Particle[] arr = new Particle[howMany]; for(int i = 0; i < howMany; i++) { arr[i] = new Particle(this); arr[i].mass /= howMany; } return arr; } That code makes it clear that the new particles are copies of the parent particle, because it used the copy constructor to make them, with exactly one attribute of them changed. Anyway, you begin to see why the keyword is "this"--it matches very naturally the language we use to describe such situations. Some computer languages, however, use different keywords. "self" is probably the most common alternate, although I believe some others use "my" instead. Either way, the reference is always to the current object.