简体   繁体   English

Java中的“ this”关键字

[英]'this' keyword in Java

I have a question regarding this in the following code. 我在以下代码中this有疑问。 In the following, this.name will set the name. 在下面, this.name将设置名称。 We could also do this using name = name , so my question is should the this pointer be used. 我们也可以使用name = name来做到这一点,所以我的问题是应该使用this指针。 This is not an homework 这不是功课

import java.io.*;

public class Employee{
    String name;
    int age;
    String designation;
    double salary;

    //This is the constructor of the class Employee
    public Employee(final String name){ //EDIT: Made parameter final
        this.name = name;
        //name= name; this is also correct
    }

    //Assign the age of the Employee  to the variable age.
    public void empAge(int empAge){
        age =  empAge;
    }

    //Assign the designation to the variable designation.
    public void empDesignation(String empDesig){
        designation = empDesig;
    }

    //Assign the salary to the variable salary.
    public void empSalary(double empSalary){
        salary = empSalary;
    }

    //Print the Employee details
    public void printEmployee(){
        System.out.println("Name:"+ name );
        System.out.println("Age:" + age );
        System.out.println("Designation:" + designation );
        System.out.println("Salary:" + salary);
    }
}
  //      name= name; this is also correct

This is not correct. 这是正确的。 It'll assign your parameter to itself. 它将为您自己分配参数。 By using the this keyword, you're declaring which name you're using (ie the field on your Employee object). 通过使用this关键字,你宣布你正在使用(即你在球场上Employee的对象)。

You may wish to name the field differently from the parameter. 您可能希望使用与参数不同的名称来命名字段。 However this means that all works well until someone automatically refactors your code to (perhaps inadvertently) declare the field and parameter as the same name! 但是,这意味着一切正常,直到有人自动重构您的代码以(可能无意间)将字段和参数声明为相同的名称为止!

For this reason you'll often see method signatures defined thus: 因此,您经常会看到这样定义的方法签名:

public Employee(final String name)

The final keyword prevents reassignment, and stops you from mistakenly reassigning the input parameter, and consequently not assigning to your field. final关键字可防止重新分配,并防止您错误地重新分配输入参数,从而避免分配给您的字段。 Note also that if you declare the field as final , then compilation will fail if you don't make an assignment to that field. 还要注意,如果您将该字段声明为final ,那么如果不对该字段进行赋值,则编译将失败。 Using final is a good way to trap such errors and also enforce the immutability of an object (often a good thing - it contributes to a more reliable solution, especially in a threaded environment). 使用final是捕获此类错误并增强对象的不变性的好方法(通常是一件好事-它有助于提供更可靠的解决方案,尤其是在线程环境中)。

Well to avoid the confusion in cases like u mentioned name=name we uses this pointer to make it clear the we here mean class variable name . 为了避免在您提到的name = name之类的情况下造成混淆,我们使用此指针来弄清楚我们这里指的是类变量name。

So to make understand the reader here in this case we use this though there can be many other cases where (this) is more useful. 因此,在这种情况下,为了使读者理解我们可以使用它,尽管在许多其他情况下,(this)更有用。

In some compilers name=name gives error as well 在某些编译器中,name = name也会给出错误

Notice that there are two things called name in your code. 注意,在代码中有两件事叫做name Your class Employee has member variable called name , and the constructor takes a parameter that's also called name . 您的Employee类具有名为name成员变量,并且构造函数采用一个也称为name的参数。

What you want to do in the constructor is set the member variable name to the same value as the parameter name . 您要在构造函数中执行的操作是将成员变量name设置为与参数name相同的值。 To access the member variable, you have to use this.name , because name refers to the parameter - because the variables have the same name, the parameter is hiding the member variable. 要访问成员变量,您必须使用this.name ,因为name引用参数-因为变量具有相同的名称,所以该参数隐藏了成员变量。

Note that name = name; 注意name = name; does not do the same thing as this.name = name; this.name = name; .

When you do name = name; 当你做name = name; , you assign the value of the parameter name to the parameter itself - not to the member variable. ,则将参数name的值分配给参数本身- 而不是成员变量。 The compiler does not magically know that the first name is supposed to mean the member variable, and the second name is supposed to mean the parameter. 编译器并不神奇地知道第一个name应表示成员变量,第二个name应表示参数。

So, you need this in this case to refer explicitly to the member variable, instead of the parameter that is hiding the member variable. 因此,在这种情况下,您需要使用this来显式引用成员变量,而不是隐藏成员变量的参数。

In this case this is just a scope resolution/disambiguation. 在这种情况下, this只是范围解析/歧义消除。

public Employee(String name){
  this.name = name;
  // the above line will assign a value of parameter to instance variable
  //      name= name; this is also correct
  // (**NO** the above line will assign a value of parameter to itself) 
}

当参数名称和类变量名称相同时,要区分它们,可以编写this.classVariable来标识类变量

When you call a variable, the pointing one is the one who is the closest to your current scope. 调用变量时,指向变量的是最接近当前作用域的变量。

So, if program is currently containing in memory a local variable toto and the wrapping class containing a field variable toto , you have to precise this keyword in order to access the field's one. 因此,如果程序当前在内存中包含一个局部变量toto ,而包装类包含一个字段变量toto ,则必须精确定义this关键字才能访问该字段的关键字。

Otherwise, the field variable is said to be shadowed by the local variable and so doing toto = toto assigns the local parameter to itself (never useful) and not what you are expecting => the field variable. 否则,该字段变量据说是由局部变量来遮蔽并且这样做toto = toto分配本地参数本身(永远有用),而不是你期待什么=>字段变量。

Why make it so hard on yourself? 为什么要对自己这么难?

Just rewrite the signature/method like this: 只需这样重写签名/方法:

public Employee(String _name) {
   name = _name;
}

Always try to avoid variable hiding or other hard-to-read constructs. 始终尝试避免变量隐藏或其他难以理解的构造。 If you want your code to be maintainable, write it in such a way that everybody can understand it immediately. 如果您希望代码可维护,请以使每个人都可以立即理解的方式编写代码。 Even if you are the only one; 即使你是唯一的一个; you might forget what you meant in time. 您可能会忘记您及时的含义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM