构造函数赋值实例变量时,是否需按惯例添加this前缀?
Should I add the
this prefix when assigning to the instance variable mappedObject? Great question—let's break this down clearly.
First, let's clarify when this is required in Java:
- You must use
thiswhen there's a naming conflict between an instance variable and a local variable (like a method parameter or a variable declared inside the method). For example, if your constructor had a parameter namedmappedObject, you'd needthis.mappedObject = mappedObject;to tell the compiler you're referring to the instance variable, not the parameter. - In your code, though, the constructor parameters are
providerandobjectMapper—no overlap withmappedObject. So in this specific case, addingthisis not mandatory; the compiler will correctly recognize that you're assigning to the instance variable without it.
Now, about the "coding convention" your colleague mentioned:
- Many teams and style guides (like Google Java Style Guide, or internal team standards) do recommend adding
thisfor all instance variable references, even when there's no naming conflict. The goal here is readability: it makes it immediately obvious to anyone reading the code that the variable is an instance member, not a local variable or parameter. This can be especially helpful in longer methods or classes with lots of variables. - But crucially, this is just a convention, not a rule enforced by the Java compiler. There's no universal "right" or "wrong" here—just what your team agrees on to keep code consistent.
To tie this back to your code:
Your original line mappedObject = new MappedObject.Builder<A, B>(...); is completely valid and correct. If your team's convention requires this, then switching to this.mappedObject = ... is fine—but you weren't wrong to omit it in the first place. Your initial understanding was spot-on: this is only strictly necessary in specific conflict scenarios.
内容的提问来源于stack exchange,提问作者Orange Receptacle
相关产品推荐
相关产品推荐

