简体   繁体   中英

Why make a class create an instance of itself?

I recently came across some code recently and although I know that it can work, I really don't see why a class would ever need to create an instance of itself within itself?

I can't find any explanation for why you would do this, only how you do it.

For example:

public class Simple1 {

  /** Main entry point. */
  public static void main(String args[]) throws ParseException {
    Simple1 parser = new Simple1(System.in);
    parser.Input();
  }

}

Execution in a Java program starts up in public static void main . Since this method is static , there is no actual instance of the main class when the program starts up, so if there needs to be an instance of that object for some reason (for example, if you subclass off of JPanel to have the main class be a window), the main method needs to manually construct it and begin calling methods on it. There's no reason it has to be this way, but it gives a convenient way to make the main method either optionally create an object of its own type (if it wants to) or instantiate lots of objects of other types and link them up as it sees fit.

Hope this helps!

In your example the object is not really creating similar objects. Your call is in a static context and thus there is no actual object involved in the execution of your main method. Unless of course we talk about the static "class object" or whatever that might be called. But it is not the same as instances of that object. Refer to basics of OO programming for why objects make sense for that.

As for the rest, sometimes it just makes sense. A Person object might have fields for children, parents, workers, managers, whatever. You could represent them as more Person objects. Then have more children of various types under it. Kinda like OO recursion. Would you create them in the object itself? If you like, why not.

Or think of a tree with nodes where a leaf is a Node object and has other Node objects as sub leaves. Or a map-reduce type algorithm that spawns new tasks of same type as a result of computations. Etc.etc.

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