【发布时间】:2012-08-12 12:38:17
【问题描述】:
分配java变量的最佳方式是什么?有什么区别?看到这个;
public class Test {
private String testString;
//getter & setter here.
public void testMethodOne() {
this.testString = "Hello World!";
}
public void testMethodTwo() {
testString = "Hello World!";
}
public void testMethodThree() {
setTestString("Hello World!");
}
}
哪个最好,this.testString = "xxx" 或 testString = "xxx" 或 setTestString("xxx")?
【问题讨论】:
-
请阅读 Joshua Bloch 的 Effective Java 中的第 13-14 条。
-
我发现不必要地使用
this.会给眼睛带来负担,但这是一个品味问题。在类内部调用setTestString是不必要的,除非您知道它除了修改值之外还有有用的副作用。 -
@AmitDeshpande 第 13 项或第 14 项与此处无关。
-
顺便说一句,这会产生编译错误,严重的是在运行时它会生成相同的字节码