static 就分配了内存空间,即编译时就为这些成员变量的实例分配了空间。
例子一:
{
static int t=1;
T1(int b)
{
t=b;
}
}
public class Static
{
T1 t1=new T1(2);
T1 t2=new T1(3);
T1 t3=new T1(4);
public Static()
{
System.out.println("t1: "+t1.t);
System.out.println("t2: "+t2.t);
System.out.println("t3: "+t3.t);
}
public static void main(String args[])
{
new Static();
}
}
<span style="font-family: Arial, Helvetica, sans-serif; font-size: 12px;"></span>
运行结果为:t1:4
t2:4
t3:4
说明statici变量只接受了最后一次的初始化,多个实例共享一个静态变量的问题
例子二:
<span style="font-family: Arial, Helvetica, sans-serif; font-size: 12px;">public class StaticInit</span>
{
static int i;
int a;
public StaticInit()
{
a=6;
System.out.println("a 的初始化"+a);
}
public static void main(String[] args)
{
new StaticInit();
}
static
{
i=5;
System.out.println("i 的初始化"+i);
}
}
运行结果为:
i 的初始化 5
a 的初始化 6
得出结果先运行了static的方法再去运行其他非静态方法