为什么要让一个类创建其自身的实例? [英] Why make a class create an instance of itself?

查看:90
本文介绍了为什么要让一个类创建其自身的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近遇到了一些代码,尽管我知道它可以工作,但我真的不明白为什么类需要在其内部创建自身的实例吗?

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.

例如:

public class Simple1 {

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

}

推荐答案

Java程序中的执行在public static void main中启动.由于此方法为static,因此在程序启动时没有主类的实际实例,因此,由于某种原因是否需要该对象的实例(例如,如果将JPanel的子类设置为(主类是一个窗口),main方法需要手动构造它并开始在其上调用方法.没有理由具有这样的方式,但是它提供了一种便捷的方式来使main方法可以选择创建自己类型的对象(如果需要)或实例化许多对象并根据需要将它们链接起来.

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.

希望这会有所帮助!

这篇关于为什么要让一个类创建其自身的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆