"this" keyword

上一篇 / 下一篇  2014-09-02 14:27:07 / 个人分类:Java

The following is a copy & paste fromhere, but explains very well all different uses of thethiskeyword:

Definition:Java’sthiskeyword is used to refer the current instance of the method on which it is used.

Following are the ways to use this:

  1. 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 thethisdenotes the local variable. If the local variable that is parameter’s name is not same as instance variable then irrespective ofthisis used or not it denotes the instance variable.

  2. Thisis used to refer the constructors

    publicJavaQuestions(Stringjavapapers){this(javapapers,true);}

    This invokes the constructor of the same java class which has two parameters.

  3. Thisis used to pass the current java instance as parameter

    obj.itIsMe(this);
  4. 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.

  5. Thiscan be used to get the handle of the current class

    ClassclassName=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

TAG:

 

评分:0

我来说两句

日历

« 2024-03-17  
     12
3456789
10111213141516
17181920212223
24252627282930
31      

数据统计

  • 访问量: 10374
  • 日志数: 15
  • 书签数: 1
  • 建立时间: 2008-12-01
  • 更新时间: 2014-09-02

RSS订阅

Open Toolbar