在 class 中创建 class 的实例是标准做法吗?

Is it standard practice create an instance of a class within that class?

我在 class Foo 中遇到了一些代码,其方法 doSomething() 创建了 class foo.

的实例
public class Foo {
    public void doSomething() {
         Foo foo1 = new Foo();
    }
}

这是标准做法吗?这似乎是一种非常奇怪的处理方式。你为什么要做这样的事情。以这种方式创建代码是否存在危险?您是否有理由这样做而不是使用其他一些做法?最后,我的直觉是任何执行此类操作的方法都应声明为静态的。对吗?

是的,这是标准做法。它不是 common(在实例方法中,在 statics 中更常见),但它是完全标准的。

Foo 中的代码在很大程度上是无关紧要的:如果代码出于某种原因需要一个 Foo 实例而不是 this,那么创建一个实例并使用它是完全正常的它。

它并不比创建不同 class:

的两个实例的方法更奇怪
class Foo {
    void method() {
        Bar b1 = new Bar();
        Bar b2 = new Bar();
        // ...
    }
}

据推测,method 需要两个 Bar 实例。同样,doSomething 显然需要 Foo 而不是 this.

您特别看到的一个地方是具有流畅接口的不可变对象,其中大多数方法 return 具有某些方面更改的对象实例。

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, ...

是的,没关系。一个很好的例子是 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
}