黑马程序员技术交流社区

标题: Runtime类为什么不能new [打印本页]

作者: 林枢    时间: 2011-7-26 22:10
标题: Runtime类为什么不能new
只能getRuntime
作者: 匿名    时间: 2011-7-26 22:22
单例模式,你看看Runtime的源代码就可以了。
Runtime的构造函数是私有的,从程序角度也不允许你直接创建。
从深层次考虑,如果你的Runtime可以随你创立,那JAVA程序的安全性将会大为降低。

建议你多了解点单例模式。类似的还有Calendar.getInstance()

public class Runtime {
    private static Runtime currentRuntime = new Runtime();

    /**
     * Returns the runtime object associated with the current Java application.
     * Most of the methods of class <code>Runtime</code> are instance
     * methods and must be invoked with respect to the current runtime object.
     *
     * @return  the <code>Runtime</code> object associated with the current
     *          Java application.
     */
    public static Runtime getRuntime() {
return currentRuntime;
    }

    /** Don't let anyone else instantiate this class */
    private Runtime() {}
作者: 匿名    时间: 2011-7-27 18:54
标题: 回复 楼主 的帖子
这是一个单例模式,Runtime的构造函数是private,那是不能new的
作者: 匿名    时间: 2011-7-27 22:57
Runtime类封装了运行时的环境。每个 Java 应用程序都有一个 Runtime 类实例,使应用程序能够与其运行的环境相连接。既然是运行时类实例,一旦程序运行就说明已经有这个实例对象了为啥还要再new实例对象呢.




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2