在学习中遇到这样一段代码,它是在一个函数内部的,我只想知道他是在什么时候运行的为什么要给这段代码加上static?
static
{
try
{
Configuration config = new Configuration();
config.addClass(Customer.class);
sessionFactory = config.buildSessionFactory();
}
catch(Exception e)
{e.printStackTrace();}
}
static
{
try
{
Configuration config = new Configuration();
config.addClass(Customer.class);
sessionFactory = config.buildSessionFactory();
}
catch(Exception e)
{e.printStackTrace();}
}
static int m = 0;
int n = 0; static {
m++;
System.out.println("the value of m now is: " + m);
} void increaseN() {
n++;
System.out.println("the value of n now is: " + n);
} public static void main(String[] args) { Foo f = new Foo(); f.increaseN();
f.increaseN();
f.increaseN(); Foo f1 = new Foo();
Foo f2 = new Foo(); }}n每次执行increaseN()方法后都会增加1. 而m只在第一次创建类Foo的实例时增加一次, 因为增加m的代码是static的, 只执行一次, 以后再创建更多的Foo的实例都不会执行了.