public static void main(String[] args)
{
new A();//1
static int num=1;//2
}
为什么2先执行?
{
new A();//1
static int num=1;//2
}
为什么2先执行?
解决方案 »
- native关键字的运用
- Java对文字或者字符的接受代码是什么啊?(初学者)
- 反射类的IllegalAccessExceptionextends如何发生??
- ..........这段GUI的 java教程 如何翻译?
- BMP图片的处理想请教各位高人!
- 关于按每行N个数打印输出的问题(附源码)
- getClass()的作用
- 请问调用notify后被选中线程的wait是立刻返回,还是等到调用notify的线程退出synchronized块后再返回?
- Class.forName("sun.jdbc.odbc.JdbcOdbcDriver")时遇到的问题,谢谢
- Java 如何进行性能分析?有工具吗
- 关于钞票换硬币的算法问题,高手请进
- 外观感觉
先执行,是因为num类属性,类属性初始化肯定在对象属性之前
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();
} ///:~
可是在方法中啊
不是因为变量,也不是因为对象,而是因为它是static只要是static,当.class文件首次载入内存的时候,它就会得到执行...对于类的初始化,首先执行static 部分,然后是构造器,然后才是成员变量的定义定义另外,可能大家都认为一个程序必须要有一个入口函数,也就是main()函数
但是,尝试一下下面的代码,就清楚static的意义了class Test
{ static
{
System.out.println("static run");
System.exit(0);
}
}