请教:
   java中有些类是不能实例化的,比如说抽象类但是最近在看java api 还有一个类runtime类,就是使应用程序能够与其运行的环境相连接为什么这个类不能实例化呢??从类的哪里设置可以提现出来,还有就是看见里面有个静态函数getRuntime(),其功能就是获取其对象,请问为什么java中要这样设置,如果runtime不能实例化,那么getRuntime()函数是不是也相当于实例化了呢??最重要的是为什么要这样设置呢?

解决方案 »

  1.   

    这个类是类似于单例模式,就是说他的构造器是私有的,你不能在new出来,这个类再加载的时候就会出现一个实例(也是唯一的一个),此实例可以通过getRuntime()获取。
      

  2.   


    让我们来看看JDK中的源码
    /**
     * Every Java application has a single instance of class 
     * <code>Runtime</code> that allows the application to interface with 
     * the environment in which the application is running. The current 
     * runtime can be obtained from the <code>getRuntime</code> method. 
     * <p>
     * An application cannot create its own instance of this class. 
     *
     * @author  unascribed
     * @version 1.78, 04/10/06
     * @see     java.lang.Runtime#getRuntime()
     * @since   JDK1.0
     */
    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() {}
    从注释我们可以看出来每一个java application只能有一个Runtime的实例,也就是楼上说的单例模式,单例模式最常见的实现办法是将构造器私有,这样的作用是Don't let anyone else instantiate this class只能由内部进行实例化 private static Runtime currentRuntime = new Runtime();外部需要Runtime对象时,只能每次都取出同一个,public static Runtime getRuntime() 这个方法是static的,不需要实例化也可以调用
      

  3.   

    Runtime rt = Runtime.getRuntime();