示例
class Parent {
static {
System.out.println("Parent's static code block...");
}
{
System.out.println("Parent's constructor code block...");
}
public Parent() {
System.out.println("Parent's constructor without arguments...");
}
}
class Children extends Parent {
private String name;
static {
System.out.println("Children's static code block...");
}
{
System.out.println("Children's constructor code block...");
}
public Children() {
System.out.println("Children's constructor without arguments...");
}
public Children(String name) {
this.name = name;
System.out.println("Children's constructor with arguments...");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class ExtendTest {
public static void main(String[] args) {
/* * ExtendTest's static code block is executed... * Parent's static code block... * Parent's constructor code block... * Parent's constructor without arguments... * ------------------------ * Parent's constructor code block... * Parent's constructor without arguments... */
/*Parent p1 = new Parent(); System.out.println("------------------------"); Parent p2 = new Parent();*/
/* * ExtendTest's static code block is executed... * Parent's static code block... * Children's static code block... * Parent's constructor code block... * Parent's constructor without arguments... * Children's constructor code block... * Children's constructor without arguments... * ------------------------ * Parent's constructor code block... * Parent's constructor without arguments... * Children's constructor code block... * Children's constructor with arguments... */
Children c1 = new Children();
System.out.println("------------------------");
Children c2 = new Children("Bob");
}
static {
System.out.println("ExtendTest's static code block is executed...");
}
}
总结
静态代码块:
1. 静态代码块只能在类中由static{}
进行声明创建,不能放在类中的方法中或其他代码块中
2. 静态代码块属于类,在类被JVM加载时被执行,只会执行一次
3. 静态代码块先于main()方法执行
4. 静态代码块用于给类初始化
构造代码块
1. 构造代码块只能在类中由{}
进行声明创建,若放在类中的方法中或其他代码块中,则称之为“局部代码块”
2. 构造代码块会在创建对象时,先于构造器执行
3. 构造代码块用于给对象进行统一初始化