1.变量是 static final 修饰的“编译期常量”,如 public static final String c = "C";
public class Test {
public static void main(String[] args) {
System.out.println(A.c);
}
}
class A {
public static final String c = "C";
static {
System.out.print("A");
}
}
运行结果如下:C
public class Test {
public static void main(String[] args) {
System.out.println(B.c);
}
}
class A {
public static final String c = "C";
static {
System.out.print("A");
}
}
class B extends A {
static {
System.out.print("B");
}
}
运行结果如下:C
public class Test {
public static void main(String[] args) {
System.out.println(B.c);
}
}
class A {
static {
System.out.print("A");
}
}
class B extends A {
public static final String c = "C";
static {
System.out.print("B");
}
}
运行结果如下:C
2.变量是 static final 修饰的“非编译期常量”,如 public static final String c = new String("C");
public class Test {
public static void main(String[] args) {
System.out.println(A.c);
}
}
class A {
public static final String c = new String("C");
static {
System.out.print("A");
}
}
运行结果如下:AC
public class Test {
public static void main(String[] args) {
System.out.println(B.c);
}
}
class A {
public static final String c = new String("C");
static {
System.out.print("A");
}
}
class B extends A {
static {
System.out.print("B");
}
}
运行结果如下:AC
public class Test {
public static void main(String[] args) {
System.out.println(B.c);
}
}
class A {
static {
System.out.print("A");
}
}
class B extends A {
public static final String c = new String("C");
static {
System.out.print("B");
}
}
运行结果如下:ABC
3.变量是static 修饰,如 public static String c = "C";
public class Test {
public static void main(String[] args) {
System.out.println(A.c);
}
}
class A {
public static String c = "C";
static {
System.out.print("A");
}
}
运行结果如下:AC
public class Test {
public static void main(String[] args) {
System.out.println(B.c);
}
}
class A {
public static String c = "C";
static {
System.out.print("A");
}
}
class B extends A {
static {
System.out.print("B");
}
}
运行结果如下:AC
public class Test {
public static void main(String[] args) {
System.out.println(B.c);
}
}
class A {
static {
System.out.print("A");
}
}
class B extends A {
public static String c = "C";
static {
System.out.print("B");
}
}
运行结果如下:ABC
public class Test {
public static void main(String[] args) {
A[] superClasses = new A[10];
}
}
class A {
static {
System.out.print("A");
}
}
运行结果为空
总结:1.通过子类引用父类的静态字段,不会导致子类的初始化
2.通过数组定义来引用类,不会触发此类的初始化
3.引用类中的常量不会导致此类的初始化