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:

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.

@sdir, the methods work fine in the small beginner's projects I'm doing, I'm just wondering if there's any long-term problems that having setters and constructors that are set up like this might cause
–
TKoLJan 18 '13 at 23:04

4 Answers
4

If a name declared as a local variable is already declared as a field
name, then that outer declaration is shadowed (§6.3.1) throughout the
scope of the local variable. Similarly, if a name is already declared
as a variable or parameter name, then that outer declaration is
shadowed throughout the scope of the local variable (provided that the
shadowing does not cause a compile-time error under the rules of
§14.4.2). The shadowed name can sometimes be accessed using an
appropriately qualified name.

For example, the keyword this can be used to access a shadowed field
x, using the form this.x. Indeed, this idiom typically appears in
constructors (§8.8):

In this example, the constructor takes parameters having the same
names as the fields to be initialized. This is simpler than having to
invent different names for the parameters and is not too confusing in
this stylized context. In general, however, it is considered poor
style to have local variables with the same names as fields.

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 this context scope.

No there's nothing wrong. The this keyword resolve the ambiguity because it tells the compiler that the l-value you are setting is the member variable(es. this.partNum) and not the input parameter(partNum).

If this is a bad practice, that's more a matter of personal taste. Some people don't like to use the same name for both the member variable and the input parameter. Personally I've use this often for several reasons: