开发者社区 问答 正文

java只有一个类,main和static 变量谁先运行?

class Go {
    static String s1 = "run";
    static String s2, s3;
    static {
        s2 = "drive car";
        s3 = "fly plane";
        print("s2 & s3 initialized");
    }
    static void how() {
       print(s1 + " or " + s2 + " or " + s3);
    }
   Go() { print("Go()"); }  
}

public class ExplicitStaticEx {
public static void main(String[] args) //main函数先运行还是static Go g1 = new Go();和static Go g2 = new Go();先运行?
{                                                       
    print("Inside main()");
    Go.how();
    print("Go.s1: " + Go.s1);       
}
static Go g1 = new Go();
static Go g2 = new Go();
 }

展开
收起
蛮大人123 2016-06-13 15:51:39 2672 分享 版权
2 条回答
写回答
取消 提交回答
  • 类先加载和初始化才可能找到入口,static 先执行。

    2019-07-17 19:36:15
    赞同 展开评论
  • 我说我不帅他们就打我,还说我虚伪

    全局对象的创建优先于入口函数的执行。
    对于ExplicitStaticEx 类来说,g1和g2是静态成员变量,
    使用一个类之前需要先对这个类进行加载,
    类加载时会执行静态成员变量的赋值和静态代码块里的内容(执行的先后顺序与代码顺序有关)
    所以会先执行static Go g1 = new Go();和static Go g2 = new Go();
    而使用Go这个类也是需要先加载的,
    因此会先执行Go类里的
    static String s1 = "run";
    static String s2, s3;
    static {
    s2 = "drive car";
    s3 = "fly plane";
    print("s2 & s3 initialized");
    }
    然后再执行new Go() 两次,即 g1 = new Go()和 g2 = new Go()
    最后执行ExplicitStaticEx里的main方法,(在eclipse里run ExplicitStaticEx这个类就是调用它的main方法)

    2019-07-17 19:36:15
    赞同 展开评论
问答分类:
问答地址: