The following is a copy & paste fromhere, but explains very well all different uses of thethis
keyword:
Definition:Java’sthis
keyword is used to refer the current instance of the method on which it is used.
Following are the ways to use this:
To specifically denote that the instance variable is used instead of static or local variable. That is,
privateStringjavaFAQ;voidmethodName(StringjavaFAQ){this.javaFAQ=javaFAQ;}
Here this refers to the instance variable. Here the precedence is high for the local variable. Therefore the absence of the
this
denotes the local variable. If the local variable that is parameter’s name is not same as instance variable then irrespective ofthis
is used or not it denotes the instance variable.This
is used to refer the constructorspublicJavaQuestions(Stringjavapapers){this(javapapers,true);}
This invokes the constructor of the same java class which has two parameters.
This
is used to pass the current java instance as parameterobj.itIsMe(this);
Similar to the above this can also be used to return the current instance
CurrentClassNamestartMethod(){returnthis;}
Note: This may lead to undesired results while used in inner classes in the above two points. Since this will refer to the inner class and not the outer instance.
This
can be used to get the handle of the current classClassclassName=this.getClass();// this methodology is preferable in java
Though this can be done by
ClassclassName=ABC.class;// here ABC refers to the class name and you need to k