We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › the this() concept ...
Page Index Toggle Pages: 1
the this() concept ... (Read 430 times)
the this() concept ...
Nov 30th, 2007, 10:49am
 
Hi,
Can someone explain the "this" concept according to an array and object oriented programming? It is not really in the processing book, is it?

I also looked at the online reference, and that example is not detailed enough for me. I'd like to know how to use it with object oriented programming - the object oriented programming is _really_ well explained in the processing book, by the way:)

Best,
am
Re: the this() concept ...
Reply #1 - Nov 30th, 2007, 11:29am
 
'this' always refers to whichever object it's used within.

Say for example you have an object which stores apples, call it a basket, and an apple object which wants to get into the basket.

There's two ways of doing it, one is that some all encompassing class which has a basket and apple object adds the apple to the basket, it can use the proper names of the objects to do this.

The other way however is that the apple knows about the basket, and puts itself in the basket. Now the apple doesn't know its own name, but it can call itself "this" and things will work out.

or in code:
Code:
//myBasket has an add(Apple a) method.
//in the global method:
Apple myApple=new Apple();
Basket myBasket=new Basket();

myBasket.add(myApple);

//in the non-global method
//in the Apple class:
void addToBasket(Basket b)
{
b.add(this); // "this" refers to this sepcific Apple
}

//and then at the global level
Apple myApple=new Apple();
Basket myBasket=new Basket();
myApple.addToBasket(myBasket); //so myApple adds itself to the basket


This example is a bit contrived since we know this Apple is called myApple but you'll have to imagine more complex cases where things aren't so straightforward and no one "global" function knows about all the constituent parts.

This is also used for example if the "addToBasket" method does some work within the Apple.. setting various internal state for example.
Re: the this() concept ...
Reply #2 - Nov 30th, 2007, 3:19pm
 
annemarie,
I do cover "this" in my book (Chapter 8 OOP). It even made it into the index (which was mysteriously created by the publisher).

ira
Re: the this() concept ...
Reply #3 - Dec 1st, 2007, 2:32pm
 
Wait, Ira.

How does an Index "mysteriously" get created by the publisher. I thought someone (you) sits there and types all those up? I know nothing about publishing, and this topic is way off-course Smiley

Great book btw, we have it in our office.
Page Index Toggle Pages: 1