Can you explain “this?”
February 12, 2008 1:58 PM   Subscribe

How do you explain the this object?

I was working with a student in Java the other day, and although Java isn’t my lingua franca, I did use it in college about 10 years ago, and I’m comfortable with OOP. But I struggled trying to explain this.

How would you go about explaining the semantics of this for an intro-level student, w/r/t Java specifically?
posted by ijoshua to Computers & Internet (29 answers total)
It's just like the pronoun 'me'. It refers to whoever is using it.
posted by demiurge at 2:00 PM on February 12, 2008

In Python it's called "self". OOP associates functions with data structures. "this" is whatever instance of the data structure the member fuction was used on.
posted by aubilenon at 2:04 PM on February 12, 2008

If I was explaining this to a friend who knows nothing about Java, I would of course use the trite "cars are objects" analogy, and the main thrust would be this.

Now if somebody calls Car A's "drive()" function, the car may need to know how much gas it has in the tank, so maybe it will call "checkForGas()". But how do you make sure that you're calling Car A's checkForGas() function and not Car B's? This is where the 'this' keyword comes into play, self.checkForGas() specifies: "call the function checkForGas() that belongs to the same object as this function does", which is in this case, Car A.
posted by onalark at 2:14 PM on February 12, 2008


What is your target person here, more specifically? Does the student understand the relationship/division between classes and instances/objects? The understanding of this is dependent on that. (Har har.)

In Objective-C, like Python, it's called self, the idea being "send a message to this instance of myself telling myself to do something". You're talking to yourself, basically. For languages that use this instead of self, you can think of it as sending a message or communicating with this specific object/instance of the class.

Same thing, different words.
posted by secret about box at 2:26 PM on February 12, 2008

Smalltalk also uses "self", and as previous posters have indicated, the receiver of the request to the same object that sent the request. onalark's illustration is a very nice one.
posted by johnvaljohn at 2:28 PM on February 12, 2008

Mikey-San raises a good point: no matter what you say, it's going to be incomprehensible to your student unless he or she knows the difference between a class and an instance of the class. The fact that this concept is hard for the student to grasp suggests that they might need a review on that topic.
posted by svolix at 2:30 PM on February 12, 2008

Just to be super pedantic... this is a pointer, not an object.

If your student is comfortable with procedural programming (non-OOP), then you might explain that when you write a class method in Java, you're writing a method that is shared by all instances of that class. The this pointer is what allows that shared method to act on the data of the particular object for which it is being called.
posted by mpls2 at 3:04 PM on February 12, 2008

The student probably knows that in java all code is generally executed within the context of some class. More specifically, at runtime, classes are instantiated. When you instantiate a class you may refer to the specific object that is created as as object instance. It is important that your student understands the difference between a class (general definition) and an object instance (specific invocation).

When you call a function or refer to a class member variable, you must specify which object instance that method or variable is a part of. So, what happens if you have an object instance, and are executing code within a member method, and want to explicitly refer to (or pass as a parameter) the object instance within which you are executing the code? That is when you use this.

The keyword this is a way to refer to the object instance within which the currently executing code is running.
posted by yoz420 at 3:09 PM on February 12, 2008

it's an internal reference to an instantiated object.
posted by blue_beetle at 3:19 PM on February 12, 2008

Probably the easiest tact here is that if you have 10 rabbits and you call the hop() method, that method needs to know which rabbit you intended to have hop.

But who is "you"? What object is sending this message? If it's a controller responsible for a field of rabbits, "this" refers to the controller, not a rabbit. (See, you gotta be careful about how you word it.)

The bottom line is that the student needs to understand what an object/instance is. After that, you can introduce the concept of member functions (instance methods for you Obj-C nerds) and member variables. Then, and only then, will the idea of this become fully graspable.

Perhaps when you get to that point, Python/Obj-C's version would clear things up. The concept is portable, and you may get better traction with the student by talking about how another language does it, and then showing them that it's exactly the same.

This would be my recommended path to experiment with:

1. Establish the concept of a class.

2. Establish the concept of an instance of a class and how it both differs from and is related to a class specifically. (Henceforth, referring to "instances of a class" as "objects".)

3. Establish the concept of a message. (Functions, methods, whatever you want to call it.)

4. Discuss the similarities and differences between a message sent to a class and a message sent to an object.

5. Describe how one object can communicate with another object.

6. Explain how an object can communicate with itself, introducing this.
posted by secret about box at 3:20 PM on February 12, 2008

Just to be super pedantic... this is a pointer, not an object.

To be even more pedantic, in Java, it's a reference.
posted by secret about box at 3:22 PM on February 12, 2008

I think it's a pretty intuitive concept... analogies shouldn't be necessary:

Fact: The only way to invoke a (non-static) method is through an instance, e.g.
    Foo x = new Foo();;
this is the name of an implicit parameter to bar(), and that parameter is assigned the value x when is called.

(Pedantic corrections to above misconceptions:

this isn't a pointer in Java. It's a pointer in C++; in Java, there are no pointers, it's an object. The confusion may occur because objects are passed by reference, which is a pointer internal to the Java runtime, but which is never exposed to the programmer.

The name "self" in Python is just convention, not a part of the language. The instance is passed explicitly as the first argument to a method; because it's explicit, you can name the variable anything you want. )

posted by qxntpqbbbqxl at 3:27 PM on February 12, 2008

(pedant-filter: I should have previewed)
posted by qxntpqbbbqxl at 3:28 PM on February 12, 2008

Wow. I wasn't confused & now I am.

I've a feeling that JScript differentiates between this and me, or between this and self.
Hopefully, I'm wrong and they all do the same thing.
posted by seanyboy at 3:36 PM on February 12, 2008

Somehow I'm reminded of that evolutionary hypothesis ... that the reason we find ourselves in a universe and world on which all the conditions are ideally suited for life to develop is that we happen to have evolved to a point at which we could observe those conditions precisely because the conditions were perfect.
posted by Araucaria at 4:12 PM on February 12, 2008

As folks have noted above, the key point here is that she understand the ideas of class/instance and execution context. If she doesn't understand the dichotomy of classes and instances, she won't understand what "this" refers to. If she doesn't understand execution context, she won't understand the scope of the "this".

If she understands those things, then I suggest that you explain that it exists primarily for disambiguation (int a = 45; this.a = a;) and secondarily to allow one really neat little trick (;). You might expound on those points excitedly. By the time she encounters anything else for which it might be used, she'll already grok Java.

And to be super pedantic, in Java this is a reference, not an object or pointer. You don't name an object in Java, but always a reference. The difference is subtle, I suppose, but it's the difference between allocating space for a member object in the enclosing object's memory space or merely allocating the 48 bytes necessary to remember where in the heap the JVM stuck the object.

class JavaClass {
byte [] bigArray = new byte[2048];

I assure you that the size of a JavaClass on the heap is *not* (2048 + overhead). It's (sizeof(byte_array_ref) + overhead). Note that this need not be the case in C/C++.

class CPPClass {
char bigArray [1024];

That has a sizeof() of 1024 on my Mactel. This never happens in Java, as everything with a name is a reference (or primitive).
posted by Netzapper at 4:45 PM on February 12, 2008

To be even more pedantic, in Java, it's a reference.

I stand corrected.
posted by mpls2 at 4:48 PM on February 12, 2008

I approve of demiurge's approach, except that I think it is easier to conceptualize it as "my" rather than "me."

So if you have a class Circle with member variable radius and method getCircumference() the following code:

public double getCircumference() {
   return 2.0 * Math.PI * this.radius;

can be conceptualized as:

public double getCircumference() {
   return 2.0 * Math.PI * my.radius;

Of course, in reality, you would just say radius instead of this.radius, but you get the idea.
posted by jedicus at 4:56 PM on February 12, 2008

It's a reference to the instance of the class you're in.

You can use it to distinguish between method variables/parameters and fields that have the same name. For example:
private String something; // this is the field

public void setSomething(String something // this is the parameter
) {
     this.something = something; // they both have the same name, which is allowed
You can't use "this" to refer to static things, though. It's only used for instances of classes.
posted by drinkcoffee at 6:20 PM on February 12, 2008

I usually say that the class is a blueprint. You can then take this blueprint and create one or more of these objects. this then simply points to that one specific object (try using the words "self awareness" or "self identity." I find that students respond well to anthropomorphism).
posted by spiderskull at 7:22 PM on February 12, 2008

My class is my house. My members are things in my house. I give all my things names. Sometimes the things that enter my house have the exact same name as things that are in my house. I can tell them apart by saying dogNamedSpot (a dog who entered my house) and this.dogNamedSpot who is always in my house. I can always say 'dogNamedSpot' and unless there is another 'dogNamedSpot' from outside my house, it is the same as this.dogNamedSpot. I can always say this.dogNamedSpot and this.deskFullOfJunk and this.bidet, but it can get tiring, so in most cases, this. is hidden in much the way that 'you' is hidden in phrases like "be nice to me" or "get out of my house."

Sometimes I want to tell other people about my house. Whenever I want to do that, I just say this (and wave around me), and that's my house. There can be many houses built like mine, but when I'm in my house, 'this' is mine.
posted by plinth at 7:31 PM on February 12, 2008

My class is my house. My members are things in my house.

Sorry, but this is yet another bad analogy. It's confusing and, frankly, inaccurate.

Don't use analogies.
posted by secret about box at 7:39 PM on February 12, 2008

(Referring both to the bit I quoted and the entire post itself, which is extremely byzantine and does not convey an accurate description of classes, instances, methods, or this/self.)
posted by secret about box at 7:42 PM on February 12, 2008

Imagine a blueprint for building robots. That's the Robot class.

The robots (built according specs from the blueprint) are instances.

The robots all have names: coghead, metalman, beeper, electroboy... but they don't know their own names.

So if coghead wants to give one of the other robots a kiss, he may say, "WANT TO KISS ELECTROBOY."

But if he wants someone to give HIM a kiss, he can't refer to himself by name, because he doesn't know his own name. But he can call himself "this." He can say, "THIS WANTS A KISS." "This" is similar to how a person with amnesia, even if he forgot his name, could still call refer to himself as "I" or "me."

Thinking back to the blueprint. Suppose it not only describes how to built the robot; it also describes what robots say in various situations. The problem is, the blueprint is the spec for ALL robots. Since all robots will be built according to the specs in the blueprint, the blueprint can't reference any specific robot.

For instance, the blueprint can't suggest: whenever a robot is thirsty, he should say, "BEEPER WANTS OIL." The blueprint is the spec for ALL robots, not just beeper. But the blueprint can suggest that robots say, "THIS WANTS OIL." Each specific robot will interpret this as being itself.

When I teach Actionscript to beginners, I make a sign that says, "I want to go to the bathroom." I put it in the middle of the classroom, and I say to the students, "Imagine you've all been struck dumb. You can't talk, so if you want permission to go to the bathroom, you have to cross to the middle of the room, get the sign, and hold it up. George, pretend you have to go to the bathroom."

George gets the sign and holds it up.

I ask the class, "Who does the 'I' refer to in the sign." People say, "George," or "since he's holding it, 'I' means 'George'."

I then ask Mary to pretend that she needs to go to the bathroom. When she holds up the sign, I ask, "Now who does the 'I' refer to?"
posted by grumblebee at 8:55 PM on February 12, 2008 [2 favorites]

Grumblebee, that's the best analogy I've seen so far in this thread. It conveys the abstraction of a class as well as the reflexive properties of 'this'. Now I'm a bit more curious about your book :)
posted by onalark at 9:42 PM on February 12, 2008

I've a feeling that JScript differentiates between this and me, or between this and self.
Hopefully, I'm wrong and they all do the same thing.

this in javascript refers to the instance, just like anywhere else. There is neither a self variable nor a me variable in javascript, although apparently some people advocate the use of a variable called self to simulate private members.

posted by !Jim at 11:19 PM on February 12, 2008 [1 favorite]

grumblebee - I'm going to steal that analogy. I like it quite a bit.
posted by spiderskull at 10:12 AM on February 13, 2008

Steal away. And don't be too impressed. You probably would have come up with just as good an analogy -- or better -- if you stayed up all night, like I used to, trying to think of analogies. Back when I was teaching full time, I would worry and worry and worry analogies, until I figured out one that worked. Whenever a student didn't understand something, I would assume that if I could just come up with the right analogy, I'd be able to help him. I spent a lot of sleepless nights.
posted by grumblebee at 11:20 AM on February 13, 2008

this is a global object that is always available and is a good bet for the first thing to try for any values you need. If it is not on this, it might be hanging off of something else that is on this.
posted by lastobelus at 12:50 AM on February 14, 2008

« Older I want it loud... but my neighbours don't!   |   Translate my snack Newer »
This thread is closed to new comments.