Documente Academic
Documente Profesional
Documente Cultură
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 p
rogram that we have declare the name of instance variable and local variables sa
me. Now to avoid the confliction between them we use this keyword. Here, this se
ction provides you an example with the complete code of the program for the illu
stration 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 len
gth and breadth while length and breadth refers to the arguments passed in the m
ethod. We have made a program over this. After going through it you can better u
nderstand.
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);
}
}