What is the meaning of “this” in Java?

后端 未结 21 2614
走了就别回头了
走了就别回头了 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:19

    Objects have methods and attributes(variables) which are derived from classes, in order to specify which methods and variables belong to a particular object the this reserved word is used. in the case of instance variables, it is important to understand the difference between implicit and explicit parameters. Take a look at the fillTank call for the audi object.

    Car audi= new Car();
    
    audi.fillTank(5); // 5 is the explicit parameter and the car object is the implicit parameter 
    

    The value in the parenthesis is the implicit parameter and the object itself is the explicit parameter, methods that don't have explicit parameters, use implicit parameters, the fillTank method has both an explicit and an implicit parameter.

    Lets take a closer look at the fillTank method in the Car class

    public class Car()
    {
       private double tank;
    
       public Car()
       {
          tank = 0;
       }
    
       public void fillTank(double gallons)
       {
          tank = tank + gallons;
       }
    
    }
    

    In this class we have an instance variable "tank". There could be many objects that use the tank instance variable, in order to specify that the instance variable "tank" is used for a particular object, in our case the "audi" object we constructed earlier, we use the this reserved keyword. for instance variables the use of 'this' in a method indicates that the instance variable, in our case "tank", is instance variable of the implicit parameter.

    The java compiler automatically adds the this reserved word so you don't have to add it, it's a matter of preference. You can not use this without a dot(.) because those are the rules of java ( the syntax).

    In summary.

    • Objects are defined by classes and have methods and variables
    • The use of this on an instance variable in a method indicates that, the instance variable belongs to the implicit parameter, or that it is an instance variable of the implicit parameter.
    • The implicit parameter is the object the method is called from in this case "audi".
    • The java compiler automatically adds the this reserved word, adding it is a matter of preference
    • this cannot be used without a dot(.) this is syntactically invalid
    • this can also be used to distinguish between local variables and global variables that have the same name
    • the this reserve word also applies to methods, to indicate a method belongs to a particular object.

提交回复
热议问题