When you write very trivial constructors (and you'll write a lot of them), then it can be somewhat frustrating to come up with parameter names.
We have generally opted for single-letter parameter names:
public Employee(String n, double s)
{
name = n;
salary = s;
}
Some programmers prefix each parameter with an "a":
public Employee(String aName, double aSalary)
{
name = aName;
salary = aSalary;
}
That is quite neat. Any reader can immediately figure out the meaning of the parameters.
Another commonly used trick relies on the fact that parameter variables shadow instance fields with the same name. For example, if you call a parameter salary, then salary refers to the parameter, not the instance field. But you can still access the instance field as this.salary. Recall that this denotes the implicit parameter, that is, the object that is being constructed. Here is an example:
public Employee(String name, double salary)
{
this.name = name;
this.salary = salary;
}
C++ convention
In C++, it is common to prefix instance fields with an underscore or a fixed letter. (The letters m and x are common choices.) For example, the salary field might be called _salary, mSalary, or xSalary. Java programmers don't usually do that.
No comments:
Post a Comment