java - Java 中的 'this' 关键字

标签 java oop this

我对以下代码中的 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/

相关文章:

Java 这个(空)

Javascript 在分配给其他变量时丢失了上下文

java - 在 LDAP 服务器中验证用户身份

Java 编程 Jsoup

PHP OOP 在实例中保存对象的实例还是仅保存 id?

Python:单独的实用程序文件或使用静态方法?

javascript - 无法通过此访问功能

java - Connection.setAutoCommit(false); 有什么用?什么时候使用Oracle数据库?

java - Java 中的正则表达式与文本文件中的任何内容都不匹配

python - python中的多个构造函数,使用继承