开发者

Question Regarding Getters & Setters

I know this might be a stupid question to many but I usually like to stick to correct/better implementation. In Java, when writing a getter/setter, would it be better to refer to the instance variable 开发者_如何学Gowith this or access it directly?

Thanks


When writing a setter you are typically forced to refer to the instance variable (not the local variable) using this in order to differentiate between the instance variable and the parameter; e.g.

public void setFoo(int foo) {
  this.foo = foo;
}

However, when writing a getter method there is typically no need to prefix the instance variable with this:

public int getFoo() {
  return foo;
}


It does not really matter as long as you refer to the proper variables.

Yet, it is a common practice to refer to the local fields with this so that you do not mix them up with local variables:

public void setField(int field)[
    this.field = field;
}


That is simply a matter of taste, although it has some particular use cases.

When subclassing, this keyword can be used for routines and variables to stress that they actually belong to super class (or this class) and not e.g., statically imported.

It's also commonly used to disambiguate parameters from local variables. E.g.,

private Foo foo;
public void setFoo(Foo foo) {
     this.foo = foo;
}


Specifying this tends to alleviate any variable scope problems you might encounter later on.

It's not necessary, though.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜