class SuperClass
{
static
{
System.out.println("superClass init");
}
public static int value=123;
}
class SubClass extends SuperClass
{
static {
System.out.println("subClass init");
}
}
public class Static1 {
public static void main(String [] args)
{
System.out.println(SubClass.value);
// SuperClass [] sca=new SuperClass[10];
// System.out.println(sca[0].value);
// System.out.println(sca[1].value);
}
}
结果:
解释:对于静态字段,只有直接定义这个字段的类才会被初始化,因此通过其子类来引用父类中定义的静态字段,只会触发父类的初始化而不会触发子类的初始化。
public class Static1 {
public static void main(String [] args)
{
//System.out.println(SubClass.value);
SuperClass [] sca=new SuperClass[10];
System.out.println(sca[0].value);
System.out.println(sca[1].value);
}
}
结果:
<pre class="java" name="code">class ConstClass
{
static
{
System.out.println("ConstClass init");
}
public static String HELLOWORLD="helloworld";
//public final static String HELLOWORLD="helloworld";
}
public class Static2 {
public static void main(String[] args)
{
System.out.println(ConstClass.HELLOWORLD);
}
}
结果:
去掉“public static String HELLOWORLD="helloworld";”, 以及下面的“//”,重新运行,结果如下:
解释: 虽然在java原码中引用了ConstClass类中的常量HELLOWORLD,但其实在编译阶段通过常量传播优化,已将将此常量的值“helloworld”存储到类Static2中的常量池中,以后Static2对常量ConstClass.HELLOWORLD的引用都转化为Static2类对自身常量池的引用了。