this keyword : Refer Current Object
- this is keyword in Java.
- We can use this keyword in any method or constructor.
- this keyword used to refer current object.
- Use this keyword from any method or constructor to refer to the current object that calls a method or invokes constructor .
Syntax : this Keyword
this.field
Example : this Keyword
class Rectangle {
int length;
int breadth;
void setDiamentions(int ln,int br)
{
this.length = ln;
this.breadth = br;
}
}
class RectangleDemo {
public static void main(String args[]) {
Rectangle r1 = new Rectangle();
r1.setDiamentions(20,10);
System.out.println("Length of Rectangle : " + r1.length);
System.out.println("Breadth of Rectangle : " + r1.breadth);
}
}
Output :
C:zubair>java RectangleDemo
Length of Rectangle : 20
Breadth of Rectangle : 10
this Keyword is used to hide Instance Variable :
void setDiamentions(int length,int breadth)
{
this.length = length;
this.breadth = breadth;
}
- length,breadth are the parameters that are passed to the method.
- Same names are given to the instance variables of an object.
- In order to hide instance variable we can use this keyword. above syntax will clearly make difference between instance variable and parameter.
Thanks you so much for this nice article about Java this keyword .
ReplyDeletekeep it up.