wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark """""THIS"""""" Watch """""THIS"""""" New topic
Author

""""THIS"""""

SHALINI PATEL
Ranch Hand

Joined: Oct 31, 2000
Posts: 41
I am posting something for the first time. Please excuse me for my mistakes.
I am confused with the use of THIS in the following context..
class Light{
//Instance variables
int n;

//constructor
public Light(int n){
this.n = n; //1. assignment to instance variable
this.somemethod(); //2.
somemethod(); //3. equivalent to call at 2.
}
void somemethod(){System.out.println(this);}
}
}
My first point is that any assignment is considered in following way DESTINATION = SOURCE or <variable>=<expression>
Now in this context, if we see then this.n is our destination which is the instance variable and n is the parameter of the constructor which is the source. So does it mean that if we have a constructor like Light(2) we assign the instance variable this.n with the value of 2. or its vice versa?
I can understand "this"(the object of the class light) being passed in somemethod() but it does not compile. This works well with threads but not here. I dont know why.
Thanks for the help.
Sunitha Sounderrajan
Ranch Hand

Joined: Sep 12, 2000
Posts: 36
hi shalini,
"this" refers to the current object.
And if you say
this.n = n;
in the constructor it means u assign the instance variable n for the current object with a value passed as a parameter through the constructor.
Try the following code and play around to get a feel of constructors and "this"

The this cannot be reference in the main method directly and the compiler will say undefined variable.
Hope this helps!
Sunitha. S

[This message has been edited by Sunitha Sounderrajan (edited October 31, 2000).]
[I added UBB CODE tags to your source code to make it more readable. Please try to use
them in the future. Learn more about UBB codes here - Ajith ]

[This message has been edited by Ajith Kallambella (edited October 31, 2000).]
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Hi Shalini,
The code you present in your post is correct except for the extraneous brace.
For your first point, you are right. <code>this.n</code> is assigned the value of <code>2</code> if you use <code>new Light(2)</code>. the things is because the parameter in your constructor has the same name as an instance variable in your class, it is the only way to perform the assignment.
For the <code>this.somemethod()</code> call, if you remove the last brace in the code, it should compile without any errors. But you shouldn't say that "this" is passed in somemethod(), but rather somemethod is called on this (the object referenced by this).
Hope this clarifies,
Beno�t
SHALINI PATEL
Ranch Hand

Joined: Oct 31, 2000
Posts: 41
So benoit do yu mean that u are assigning the instance variable n a value 2. Why do yu want to do that? You can say it directly that int n= 2. I hope yu get me.

Thanks
SHALINI PATEL
Ranch Hand

Joined: Oct 31, 2000
Posts: 41
Sunita, I still cant follow why does it gives an undefined variable, can yu explain in detail..
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Shalini,
I'm sorry of my explanation which might not have be clear enough. What is called instance variable is not the variable that is passed in parameter, but the variable in the class instead.
Let's take another example (instance variables appear in red).

This code looks fine except for one thing. It is not very nice to always have to refer to variables prefixed with an underscore in your class implementation, where you could have named them simply x or y. So I make the following changes:

This now look better, but it won't work because the variables passed in parameter has the same names as my instance variables
So, I need a way to reference my instance variable x, so that the compiler knows which version of x and y I am refering to. Hopefully, the use of this can solve the problem. The this keyword references the instance of my object. The code then looks like this:

Now the compiler knows on lines 8 and 9 that we are refering to the instance variable of the object rather than to the parameter.
Hope it is more understandeable,
Beno�t
[This message has been edited by Beno�t d'Oncieu (edited October 31, 2000).]
SHALINI PATEL
Ranch Hand

Joined: Oct 31, 2000
Posts: 41
Thanks benoit, that really helped..
Still one silly question, remains unanswered.
In your example you have constructor Point(int x, inty) and this constructor would be explicitly initialized somewhere say Point(5,5)Ok.. So why do yu want to have that this.x=x here. What is the need of those instance variables, when yu can explicity initialize the parameters of the contructors as I explained above.. I hope I dont sound so silly.I cant see any practical use of it.
Thanks again for everything.
yogesh sood
Ranch Hand

Joined: Aug 31, 2000
Posts: 108
see what im getting from ur question is that u want to use this in constructor call .
There are mainly two use of this clause:

class Banana { void f(int i) { /* ... */ } }
Banana a = new Banana(), b = new Banana();
a.f(1);
b.f(2);
If there�s only one method called f( ), how can that method know whether it�s being called for the object a or b?
compiler does some undercover work for you. There�s a secret first argument passed to the method f( ), and that argument is the reference to the object that�s being manipulated. So the two method calls above become something like:
Banana.f(a,1);
Banana.f(b,2);
This is internal and you can�t write these expressions and get the compiler to accept them, but it gives you an idea of what�s happening.

Suppose you�re inside a method and you�d like to get the reference to the current object. Since that reference is passed secretly by the compiler, there�s no identifier for it. However, for this purpose there�s a keyword: this. The this keyword�which can be used only inside a method�produces the reference to the object the method has been called for. You can treat this reference just like any other object reference. Keep in mind that if you�re calling a method of your class from within another method of your class, you don�t need to use this; you simply call the method. The current this reference is automatically used for the other method. Thus you can say:
class Apricot {
void pick() { /* ... */ }
void pit() { pick(); /* ... */ }
}
Inside pit( ), you could say this.pick( ) but there�s no need to. The compiler does it for you automatically. The this keyword is used only for those special cases in which you need to explicitly use the reference to the current object. For example, it�s often used in return statements when you want to return the reference to the current object:

// Simple use of the "this" keyword.
public class Leaf {
int i = 0;
Leaf increment() {
i++;
return this;
}

void print() {
System.out.println("i = " + i);
}
public static void main(String[] args) {
Leaf x = new Leaf();
x.increment().increment().increment().print();
}
} ///:~
Because increment( ) returns the reference to the current object via the this keyword, multiple operations can easily be performed on the same object.

Now make following change in ur code;
class Light{
int n;
//constructor

public Light(rt n){
this.n = n; //1. assignment to instance variable
this.somemethod(); //2.
System.out.println("Inconstructer");
n.somemethod(); //3. equivalent to call at 2.
}

public Light(){}

public static void main(String args[]){
new Light().add();
}

void somemethod(){
System.out.println(this);}

void add() //line 7
{
new Light(this);
}

}
now at line 7 when u call Light constructor it is constructor no.1 called with reference of object create in main
in
Other use

In a constructor, the this keyword takes on a different meaning when you give it an argument list: it makes an explicit call to the constructor that matches that argument list. Thus you have a straightforward way to call other constructors:
class student {
int Rn;
String Name;
String Ph;

student(String Name,String Ph){
this.Name=Name;
this.Ph=Ph;
/*......ur code*/}

student(int Rn){
this("Yogesh","111111");//it must be first statement and can be used once
this.Rn=Rn
}

while you can call one constructor using this, you cannot call two. In addition, the constructor call must be the first thing you do or you�ll get a compiler error message
u cannot use it to call constructor in other method .
i.e this(argument) will be error if used somewhere else than Constuctor.
following is rule of Thumb
* The keyword this may be used only in the body of an instance method or constructor, or in the initializer of an instance variable of a class. If it appears anywhere else, a compile-time error occurs
There is no this for staic methods .
let see what u have learned guess the output of following class

class Strange{
public String toString(){
return this.toString();
}
public staic void main(String yogi[]){
Sytem.out.println(new Strange());
}
}
above topic is well discussed in Chapter 4 of
Thinking in java u can get free download of that book
at www.bruceeckel.com
Hope this will Help


If its green its biology if its stinkks its chemistry if it has numbers it is Maths and if it doesn't work its TECHNOLOGY
yogesh sood
Ranch Hand

Joined: Aug 31, 2000
Posts: 108
i got it twice !!!sorry
[This message has been edited by yogesh sood (edited November 01, 2000).]
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Shalini,
Now, I understand what you meant. The idea behind any class is that you may use them to instanciate more than one instance. Whith the class Point I exposed in my previous post, an application might use it to create several Point objects like this:
(instance variables in red, instance objects in green)

Here, there are 7 different instances of our Point class and each instance will own its own copies of the variables x and y. Try to run the code to see the results. That why classes (and instance variables) are so powerfull !
Cheers,
Beno�t
Sunitha Sounderrajan
Ranch Hand

Joined: Sep 12, 2000
Posts: 36
Shalini,
The "this" keyword is used inside any instance method to refer to the current object. The value "this" refers to the object which the current method has been called on. The this keyword can be used where a reference to an object of the current class type is required. Methods with the keyword static (class methods) cannot use this.
The compiler says undefined variable because this can only can be refrenced in instance methods.
Let me know if this is not clear.
Good Luck.
Sunitha. S
SHALINI PATEL
Ranch Hand

Joined: Oct 31, 2000
Posts: 41
THANKS EVERYBODY....
I GOT IT..
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: """"THIS"""""