I've come across some code in class Foo with method doSomething() which creates an instance of class foo.
public class Foo {
public void doSomething() {
Foo foo1 = new Foo();
}
}
Is this standard practice? It seems like a very odd way of going about things. Why would you want to do something like this. Are there dangers of creating code in this way? Is there a reason you would want to do this instead of using some other practice? And finally, my intuition is that any method that did this sort of thing should be declared static. Is that correct?
答案 0 :(得分:5)
Yes, this is standard practice. It's not common (in an instance method, more common in static
s), but it's perfectly standard.
The code being in Foo
is largely irrelevant: If the code needs a Foo
instance other than this
for some reason, then it's perfectly normal to create an instance and use it.
It's not really any more odd than a method that creates two instances of a different class:
class Foo {
void method() {
Bar b1 = new Bar();
Bar b2 = new Bar();
// ...
}
}
Presumably, method
needs both Bar
instances. Similarly, doSomething
apparently needs a Foo
other than this
.
One place you particularly see this is immutable objects with fluent interfaces, where most methods return an instance of the object with some aspect changed.
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;
}
// ...
}
Usually the withX
methods are more interesting than that, but you get the idea... String
is an example of this, as 5tingr4y points out: toUpperCase
, substring
, ...
答案 1 :(得分:1)
是的,没关系。一个很好的例子是binary tree,它(通常)在父节点中创建子节点以增长:
class Node {
Node left, right;
int value;
Node (int i) {
value = i;
}
void add(int i) {
if (i < value)
left = new Node(i); // must create Nodes within Nodes
else
right = new Node(i); // must create Nodes within Nodes
}