why

public static void main(String[] args)
{
    new A();//1
    static int num=1;//2
}
为什么2先执行?

解决方案 »

  1.   

    class A我没写啊只是举个例子
      

  2.   

    我得意思是说static 不能修饰局部变量我明白你的意思static int num=1;//2
    先执行,是因为num类属性,类属性初始化肯定在对象属性之前
      

  3.   

    class Bowl {
      Bowl(int er) {
        System.out.println("Bowl(" + er + ")");
      }
      void f(int er) {
        System.out.println("f(" + er + ")");
      }
    }class Table {
      static Bowl b1 = new Bowl(1);
      Table() {
        System.out.println("Table()");
        b2.f(1);
      }
      void f2(int er) {
        System.out.println("f2(" + er + ")");
      }
      static Bowl b2 = new Bowl(2);
    }class Cupboard {
      Bowl b3 = new Bowl(3);
      static Bowl b4 = new Bowl(4);
      Cupboard() {
        System.out.println("Cupboard()");
        b4.f(2);
      }
      void f3(int er) {
        System.out.println("f3(" + er + ")");
      }
      static Bowl b5 = new Bowl(5);
    }public class StaticInitialization {
      static Test monitor = new Test();
      public static void main(String[] args) {
        System.out.println("Creating new Cupboard() in main");
        new Cupboard();
        System.out.println("Creating new Cupboard() in main");
        new Cupboard();
        t2.f2(1);
        t3.f3(1);
        monitor.expect(new String[] {
          "Bowl(1)",
          "Bowl(2)",
          "Table()",
          "f(1)",
          "Bowl(4)",
          "Bowl(5)",
          "Bowl(3)",
          "Cupboard()",
          "f(2)",
          "Creating new Cupboard() in main",
          "Bowl(3)",
          "Cupboard()",
          "f(2)",
          "Creating new Cupboard() in main",
          "Bowl(3)",
          "Cupboard()",
          "f(2)",
          "f2(1)",
          "f3(1)"
        });
      }
      static Table t2 = new Table();
      static Cupboard t3 = new Cupboard();
    } ///:~
      

  4.   

    think in java的,main()为啥static Table t2 = new Table();和static Cupboard t3 = new Cupboard();先执行????
      

  5.   

    先执行,是因为num类属性,类属性初始化肯定在对象属性之前
    可是在方法中啊
      

  6.   

    ......看错了,谢谢interpb(曾曾胡)
      

  7.   


    不是因为变量,也不是因为对象,而是因为它是static只要是static,当.class文件首次载入内存的时候,它就会得到执行...对于类的初始化,首先执行static 部分,然后是构造器,然后才是成员变量的定义定义另外,可能大家都认为一个程序必须要有一个入口函数,也就是main()函数
    但是,尝试一下下面的代码,就清楚static的意义了class Test
    { static
    {
    System.out.println("static run");
    System.exit(0);
    }
    }