What is the meaning of “this” in Java?

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

    (I know Im late but shh Im being the sneaky boi you never saw me)

    The this keyword in most Object Oriented programming languages if not all means that its a reference towards the current object instance of that class. It's essentially the same thing as calling on that object from outside of the method by name. That probably made no sense so Ill elaborate:

    Outside of the class, in order to call something within that instance of the object, for example a say you have an object called object and you want to get a field you would need to use

    object.field
    

    Say for instance you are trying to access object.field from inside of your class in say, your constructor for example, you could use

    this.field
    

    The this keyword essentially replaces the object name keyword when being called inside of the class. There usually isn't much of a reason to do this outside of if you have two variables of the same name one of which being a field of the class and the other just being a variable inside of a method, it helps decipher between the two. For example if you have this: (Hah, get it? this? Hehe .... just me? okay :( I'll leave now)

    public String Name;
    //Constructor for {object} class
    public object(String Name){
        Name = Name;
    }
    

    That would cause some problems, the compiler wouldn't be able to know the difference between the Name variable defined in the parameters for the constructor and the Name variable inside of your class' field declarations so it would instead assign the Name parameter to.... the value of the Name parameter which does nothing beneficial and literally has no purpose. This is a common issue that most newer programs do and I was a victim of as well. Anyways, the correct way to define this parameter would be to use:

    public String Name;
    //Constructor for {object} class
    public object(String Name){
        this.Name = Name;
    }
    

    This way, the compiler knows the Name variable you are trying to assign is a part of the class and not a part of the method and assigns it correctly, meaning it assigns the Name field to whatever you put into the constructor.

    To sum it up, it essentially references a field of the object instance of the class you are working on, hence it being the keyword "this", meaning its this object, or this instance. Its a good practice to use this when calling a field of your class rather than just using the name to avoid possible bugs that are difficult to find as the compiler runs right over them.

提交回复
热议问题