1、如果静态属性 在 静态代码块前面
class Foo {
public Foo() {
System.out.println("我是 Example 的静态属性 foo ");
System.out.println(" 未修改的静态属性 值为 ====> " + Example.staticVariable);
Example.staticVariable = 2;
System.out.println(" 修改静态属性 值为 ====> " + Example.staticVariable);
}
}
class Example {
static Foo foo = new Foo();
static int staticVariable = 1;
static {
System.out.println("静态块执行");
staticVariable = 3;
System.out.println(" 修改静态属性值为===>" + staticVariable);
}
}
public class Main {
public static void main(String[] args) {
System.out.println( "main方法执行:" + Example.staticVariable);
}
}
运行结果
放在前面的静态属性先运行
如果静态代码块 放在前面
class Foo {
public Foo() {
System.out.println("我是 Example 的静态属性 foo ");
System.out.println(" 未修改的静态属性 值为 ====> " + Example.staticVariable);
Example.staticVariable = 2;
System.out.println(" 修改静态属性 值为 ====> " + Example.staticVariable);
}
}
class Example {
static int staticVariable = 1;
// 静态代码块
static {
System.out.println("静态块执行");
staticVariable = 3;
System.out.println(" 修改静态属性值为===>" + staticVariable);
}
// 静态属性Foo
static Foo foo = new Foo();
}
public class Main {
public static void main(String[] args) {
System.out.println( "main方法执行:" + Example.staticVariable);
}
}
运行结果
标签:静态,System,staticVariable,println,加载,Example,类中,out From: https://blog.csdn.net/volming36337/article/details/142601289前面的静态块先运行了