File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes problem with understanding the use of this Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "problem with understanding the use of this" Watch "problem with understanding the use of this" New topic
Author

problem with understanding the use of this

Staf Pinoy
Greenhorn

Joined: Apr 28, 2014
Posts: 4
Hello

I have a problem with understanding the use of the word "this" in java. I don't understand the explanation that was given to me in school and even after some research I can't find an explanation that suits me.
I found this explanation on a website but i don't quite get it:

this refers to the current object.

Each non-static method runs in the context of an object. So if you have a class like this:




Then calling frobnicate() on new MyThisTest() will print

1
42
MyThisTest a=42

So effectively you use it for multiple things:

clarify that you are talking about a field, when there's also something else with the same name as a field
refer to the current object as a whole
invoke other constructors of the current class in your constructor



The this(42); I understand , it just tells you that in the constructor that you're writing (this constructor, in this case) you want a to be 42. (correct me if i'm wrong)

But after that I don't understand it anymore.


The first line I do understand. no special things there.
But the second line, this.a, i would think that the a they refer to in that line is the a in the method frobnicate() itself. Because ,this, refers to THIS thing, so wouldn't it be logical that the a they refer to is the one that's equal to 1?
And the third one is a complete mystery for me. Because i think an object is a result of a class. You write a class and from that class you make objects? So i don't get how you can refer to THIS entire object, what object is THIS object??

I probably don't understand fully what an object is in java, maybe explaining that first would help me a lot already.

My apologies if my writing is unclear and pure chaos but I'm not that good in explaining myself .

Thanks in advance!

PS: i only worked with java in Greenfoot and a bit of processing.
Mike. J. Thompson
Ranch Hand

Joined: Apr 17, 2014
Posts: 263
    
    5
To understand the this keyword you need an understanding of the following things (which form the foundations of object oriented programming in Java so are very important):

1) Classes
2) Objects (and there relation to classes)
3) The static and non-static context

1) Classes

A class is like a blueprint. When you define a class you describe all the features of an entity. What data do you need to describe your entity (the class fields). What operations can you perform on that data (the class methods). How do you make instances of your entity (your class constructors).

2) Objects

Objects are instances of classes. You write the class definition once, but use that blueprint to produce many different instances of that entity. Each insurance will get its own copy of the fields and each instance can have different values for its field. All instances of a class are independent of each other, and if you change one of the instances you don't change the others.

Let's take cars as an example. Ford will have somewhere a specification for the Ford Focus. They will have got their engineers to have produced the design and written it down once.

They will then use that design to make instances of physical Ford Focus cars. Each car is made from the same design and is essentially the same, but they are not physically connected. If you open your car door my car door stays shut. If you start your engine mine stays turned off. If you drive your car your car's mileage counts up, but mine stays the same.

And this is exactly the way it is with objects. But how does this happen?

3) Static and non-static contexts.

This is a little abstract, but the context in Java describes which object your code is currently applying to.

The static context does not apply to any object. Fields that are static belong to the class and all objects of that class share a single instance of that field. Methods that are static belong to the class and can only see fields that are static, in the static context. Going back to the ford example, the number of wheels on the car could be a static variable, because all of the cars will have 4 wheels. Never 2, never 6, always 4.

The non-static context applies to objects. This is why non-static fields apply to a specific instance. If you make a change to a non-static field it only changes the value for the object that you are currently in the context of. This means that you can have many different instances of a class that are all in different states. You car can be driving while mine is stationary.

4) Transitioning from the static context to the non-static context.

When you start a program you are in the static context. You can tell this because the main method is static. So how do you access things in the non static context? The static context does not have access to non-static fields afterall. How does your code get access to non-static fields, and how does it know which object it is referring to?

The answer is that you use object references. You create instances of your class and assign the instances to references. These references can be used to access the non-static context of the instance they are attached to.



The code above is in the static context. It creates 2 car objects, and assigns them to two different references.

When the drive() method is called on car1 this transitions into the non-static context of the object that car1 is referencing.

5) The this keyword.

In your class definition you have non-static fields and non-static methods that can access those fields as I mentioned above. But you only write those fields and methods once. How does your code know which object it is running in the context of?

The answer is the this reference. Whenever you are inside a non-static method an implicit reference is created for you called this and accessed using the this keyword. You don't need to declare this reference, it is always there for you in non-static methods and constructors. It refers to the object that you are in the context of.

When you call a non-static method as we did above, you move into the context of the object referenced by the reference you use. The this reference is automatically set to point to the same object as the reference you used to call the method.



When we called car1.drive() above this will run the method shown above. The this reference will point to the same object that car1 points to. This is why we start the engine in car1 and not car2.

6) The difference between this and this()

If you write this(), that is a call to a constructor. You can only do this on the first line of a constructor, so you use it to call one constructor from another. This is similar to method overloading, and means you can avoid duplicating code in all of your constructors.
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4181
    
  21

Staf Pinoy wrote:


The first line I do understand. no special things there.
But the second line, this.a, i would think that the a they refer to in that line is the a in the method frobnicate() itself. Because ,this, refers to THIS thing, so wouldn't it be logical that the a they refer to is the one that's equal to 1?

Well, the thing is, you shouldn't think of a method as a thing - it isn't, it is more of an action, what a thing does. Objects (instances of classes) are the things, methods are what those things do, and instance variables are what those things have. So this refers to a thing, which can only be an Object, an instance of the class. So this.a refers to the a which this thing has.

Think of this like the possessive pronoun 'My'. For example, I can play with a ball, or I can play with My ball. If I were to create a method to play with a ball it might be:

Except, instead of saying my.ball Java uses this.ball.

Note that this is confusing, not just to you. Although you can use this to disambiguate references to variables in the instance scope from those in the local scope, the better practice is to name your local variables something different than the instance variables to avoid confusion.


And the third one is a complete mystery for me. Because i think an object is a result of a class. You write a class and from that class you make objects? So i don't get how you can refer to THIS entire object, what object is THIS object??

The third print statement in your snippet posted above is this: System.out.println(this);.

A class is a blueprint, the instructions for what the certain types of Objects have and how they act, like a blueprint for a building or the DNA of a person. An instance is an Object which was build based on those blueprints. And this references just one instance/Object based on that blueprint.

And this is where the 'My' analogy sort of falls apart. this isn't a pronoun, it is a noun, an Object. It is more akin to 'Me' than 'My' (except saying me.ball doesn't make for good English grammar). When I talk about Me, I am talking about one particular instance of a Person, built from the Person-type DNA/blueprint, but unique and distinct from all other instance of Person. To me, I am always 'Me' and all of the stuff I own I call 'Mine' and all the things I do I call 'My actions'. Of course to you (another instance of a Person) you are 'Me', and you would refer to your things as Mine (and you better not call My things Mine or we are in trouble.)

So in that line of code, this is the Object itself. In that line of code you are printing out the results of the toString() method for this Object, because when System.out.println() gets passed an Object, it calls that Object's toString() method, and this is an Object.

The this(42); I understand , it just tells you that in the constructor that you're writing (this constructor, in this case) you want a to be 42. (correct me if i'm wrong)

Not precisely. Don't try to force programming constructs into real-world logic, it doesn't work. The this() constructor construct I consider a slightly different beast than the this keyword alone. When used as the first line of a constructor, it doesn't really refer to the Object, because the Object doesn't exist yet, it just lets you call a different constructor in the same class. When you do this(42); all you are doing is calling the MyThisTest(int a) constructor, passing it a value of 42.


Steve
Staf Pinoy
Greenhorn

Joined: Apr 28, 2014
Posts: 4
Wow, this is amazing. You both helped me a lot. Steve's explanation was a bit easier to understand but the example with the cars from Mike was fantastic.

I'll go and make some exercises now. Hopefully I'll get the hang of it!

Thanks a lot, both of you!
Mike. J. Thompson
Ranch Hand

Joined: Apr 17, 2014
Posts: 263
    
    5
Glad you found it useful. Sorry if my post didn't read well, but I posted it on my phone. I would have liked to have used more code examples, but they are a little fiddly on a phone.

When you've had a chance to play around a bit feel free to ask more questions
Giovanni Montano
Ranch Hand

Joined: Apr 29, 2014
Posts: 78
    
    1
Mike. J. Thompson wrote:To understand (...CUT)

I understood Mike, good stuff thank you
Mike. J. Thompson
Ranch Hand

Joined: Apr 17, 2014
Posts: 263
    
    5
You're welcome, I'm glad it was helpful.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: problem with understanding the use of this