this keyword : Refer Current Object in Java Programming
- 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
Image may be NSFW.
Clik here to view.
Live 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:Priteshjava>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.
The post this keyword : Refer Current Object in Java Programming appeared first on Learn Java Programming.