hi , i know that " this " keyword or reference is used for two ways
i had understand the first one but i didnt understand the second one , i have google it but didnt find what i was looking for , so please any one here can teach me the second use of " this " keyword
with a simple and sweet " sample program " as i m just a java beginer , just 2 weeks ago i had started learning java.
thanksss.
What you need to grasp is that the "this" keyword in a Java program always refers to the object on which the method you're currently in was called (the callee of the method).
So to illustrate with the help of an example, suppose that you have a Shape class with a getRenderer() method, where getRenderer() returns a Renderer object that can draw the shape onto the screen.
Suppose further that the Renderer class has a constructor that takes as a parameter the Shape object that it should draw. Then the getRenderer() method of the Shape class might look like this:
So this method returns a new Renderer object that draws the Shape object on which the getRenderer() method was called (this).
naved momin wrote:thanks ..can you also explain me
i didnt understand . properly yet .
That is what Bernhard explained above.
You can regard this as a kind of special variable, that refers to the object that the currently running method was called on. Here is another example:
now 80% is clear , but i didnt understand what do you mean by
what is hapening over here is we have created two reference variable i.e e and example which points to the same object i.e " new Example() ", and we are calling methodOne() in which we have specified but what does " this " is here ...do we are passing "example reference-variable " here to " another reference-variable e " as an argument .
When you call a (non-static) method, you always call it on some object. Look at the main method in my example:
In the second line, we are calling methodOne on example. When we then go to methodOne, then inside the method this will refer to the Example object that methodOne was called on.
To translate it to human language, using Rob's suggestion:
Line 19: Main says: "example, execute methodOne!"
Line 10: example now gets to methodOne, and it says: "methodTwo, execute, I'm passing you myself (this)!"
hello to all,
'this' keyword has only one meaning that it has the address of currently calling object or intance. Because it stores the address of currently calling object so it has multiple uses which can be.....we can initilize the fields, this can also be passed in constructors as a parameter....or in some method...etc
i will show you example which will represent the applications of 'this' keyword..
1)
class A
{
int a,b;
public void set()
{
this.a=5;
this.b=6;
}
}
class B
{
public static void main(String s[])
{
A obj=new A();
obj.set();
System.out.println(obj.a+""+obj.b)
}
}