简体   繁体   中英

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

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?

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

Yes, it's OK. A good example is a binary tree , which (usually) creates child nodes within the parent node to grow:

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM