Issue
I have a question regarding this
in the following code. In the following, this.name
will set the name. We could also do this using name = name
, so my question is should the this
pointer be used. 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);
}
}
Solution
// 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 (i.e. the field on your Employee
object).
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. Note also that if you declare the field as final
, then compilation will fail if you don't make an assignment to that field. 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).
Answered By - Brian Agnew
Answer Checked By - Senaida (JavaFixing Volunteer)