How to use "this" keyword in java

The keyword this is useful when you need
to refer to instance of the class from its method. The keyword helps us to avoid
name conflicts. As we can see in the program that we have declare the name of
instance variable and local variables same. Now to avoid the confliction between
them we use this keyword. Here, this section provides you an example
with the complete code of the program for the illustration of how to what is this
keyword and how to use it.
In the example, this.length and this.breadth
refers to the instance variable length and breadth while length and breadth
refers to the arguments passed in the method. We have made a program over this. After going
through it you can better understand.
Here is the code of the program:
class Rectangle{
int length,breadth;
void show(int length,int breadth){
this.length=length;
this.breadth=breadth;
}
int calculate(){
return(length*breadth);
}
}
public class UseOfThisOperator{
public static void main(String[] args){
Rectangle rectangle=new Rectangle();
rectangle.show(5,6);
int area = rectangle.calculate();
System.out.println("The area of a Rectangle is : " + area);
}
}
|
Output of the program is given below:
C:\java>java UseOfThisOperator
The area of a Rectangle is : 30 |
Download this
program

|
Current Comments
5 comments so far (post your own) View All Comments Latest 10 Comments:Your example is really beneficial for beginners like me.
Posted by jujahar on Friday, 01.25.08 @ 14:29pm | #46114
Why to use this?
Posted by nilam shaikh on Saturday, 01.5.08 @ 16:29pm | #44567
plz could u explain me wt tdoes the below written statement mean
import java.this.*;
Posted by sana fatima on Monday, 11.12.07 @ 19:04pm | #36979
what does this statement mean
import java.this.*;
Posted by sana fatima on Monday, 11.12.07 @ 19:02pm | #36978
Thanks ... for the help . It was really precise and useful.
Posted by Avinash on Wednesday, 04.4.07 @ 23:55pm | #13356