What is the meaning of “this” in Java?

后端 未结 21 2606
走了就别回头了
走了就别回头了 2020-11-21 05:41

Normally, I use this in constructors only.

I understand that it is used to identify the parameter variable (by using this.something), if i

相关标签:
21条回答
  • 2020-11-21 06:21

    The this Keyword is used to refer the current variable of a block, for example consider the below code(Just a exampple, so dont expect the standard JAVA Code):

    Public class test{
    
    test(int a) {
    this.a=a;
    }
    
    Void print(){
    System.out.println(a);
    }
    
       Public static void main(String args[]){
        test s=new test(2);
        s.print();
     }
    }
    

    Thats it. the Output will be "2". If We not used the this keyword, then the output will be : 0

    0 讨论(0)
  • 2020-11-21 06:22

    The following is a copy & paste from here, but explains very well all different uses of the this keyword:

    Definition: Java’s this keyword 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,

      private String javaFAQ;
      void methodName(String javaFAQ) {
          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 of this is used or not it denotes the instance variable.

    2. This is used to refer the constructors

       public JavaQuestions(String javapapers) {
           this(javapapers, true);
       }
      

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

    3. This is 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

      CurrentClassName startMethod() {
           return this;
      }
      

      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. This can be used to get the handle of the current class

      Class className = this.getClass(); // this methodology is preferable in java
      

      Though this can be done by

      Class className = ABC.class; // here ABC refers to the class name and you need to know that!
      

    As always, this is associated with its instance and this will not work in static methods.

    0 讨论(0)
  • 2020-11-21 06:22

    this is a reference to the current object: http://download.oracle.com/javase/tutorial/java/javaOO/thiskey.html

    0 讨论(0)
提交回复
热议问题