I have an IDE which I can use to automatically create constructors and setters for instance variables, but I was wondering if the way that it creates them is possibly not best practice. Here is what it does:
private String partNum;
private String partDesc;
private int quant;
private double price;
public Invoice( String partNum, String partDesc, int quant, double price )
{
this.partNum = partNum;
this.partDesc = partDesc;
this.quant = quant;
this.price = price;
}
It’s the ‘this.name’ thing that I’m worried about, as well as the constructor labeling the parameters the same names as the variables it’s constructing. The setter also does the same thing — uses a parameter name that’s the same as the name of the variable it’s setting, and uses this.name.
So, is there anything wrong with this?
What you are witnessing is pretty standard Java practice, and is even mentioned in the Java Language Specification:
When local variables to a method have the same name as class variables, they effectively ‘shadow’ or hide those variables. But you can still access the class variables by referring to them via the
thiscontext scope.