Java中的'this'关键字

Raj*_*eev 1 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Bri*_*new 9

  //      name= name; this is also correct
Run Code Online (Sandbox Code Playgroud)

这是正确的.它会将您的参数分配给自己.通过使用this关键字,你宣称哪个你使用(即字段中输入您的名字Employee对象).

您可能希望以与参数不同的方式命名字段.然而,这意味着一切都运行良好,直到有人自动重构您的代码(可能是无意中)声明字段和参数为同一个名称!

因此,您经常会看到定义的方法签名:

public Employee(final String name)
Run Code Online (Sandbox Code Playgroud)

final关键词阻止重新分配,并停止从你重新分配错误输入参数,因此不会分配给你的领域.另请注意,如果将字段声明为final,则如果不对该字段进行分配,则编译将失败.使用final是一种捕获此类错误的好方法,并且还强制实现对象的不变性(通常是一件好事 - 它有助于提供更可靠的解决方案,尤其是在线程环境中).