我对以下代码中的 this
有疑问。在下文中,this.name
将设置名称。我们也可以使用 name = name
来做到这一点,所以我的问题是是否应该使用 this
指针。这不是作业
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
关键字,您声明了您正在使用的名称(即您的Employee
对象上的字段)。
您可能希望以不同于参数的方式命名该字段。然而,这意味着一切正常,直到有人自动重构您的代码以(可能无意中)将字段和参数声明为相同的名称!
因此,您经常会看到这样定义的方法签名:
public Employee(final String name)
final
关键字可防止重新分配,并阻止您错误地重新分配输入参数,从而不会分配给您的字段。另请注意,如果您将 field 声明为 final
,那么如果您不对该字段进行赋值,编译将失败。使用 final
是捕获此类错误并强制对象的不变性 的好方法(通常是一件好事 - 它有助于提供更可靠的解决方案,尤其是在线程中环境)。
关于java - Java 中的 'this' 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12705895/