是的,這是標準做法。這不是常見(在實例方法中,更常見於static
s),但它是完全標準的。
Foo
中的代碼在很大程度上是無關緊要的:如果代碼由於某種原因需要Foo
以外的其他實例,則創建實例並使用它是非常正常的。
這不是真的比任何一個創建不同類的兩個實例的方法更奇:
class Foo {
void method() {
Bar b1 = new Bar();
Bar b2 = new Bar();
// ...
}
}
據推測,method
需求都Bar
實例。同樣,doSomething
顯然需要Foo
而不是this
。
你特別看到的一個地方是具有流暢接口的不可變對象,其中大多數方法都會返回對象的一個實例,並改變了某些方面。
public class Thingy {
private int a;
private int b;
public Thingy(a, b) {
this.a = a;
this.b = b;
}
public Thingy withA(int newA) {
return new Thingy(newA, this.b);
}
public Thingy withB(int newB) {
return new Thingy(this.a, newB);
}
public int getA() {
return this.a;
}
public int getB() {
return this.b;
}
// ...
}
通常withX
方法比這更有趣,但你的想法... String
就是這樣的一個例子,作爲5tingr4y指出:toUpperCase
,substring
,...
恕我直言,這不是,是非常罕見的(除非該方法是靜態的)。 –