静态代码块、非静态代码块、构造函数执行顺序
/**
* 类的实例化顺序,静态代码块、非静态代码块、构造函数、
* @author MING
*/
class Person {
static String name = "父类静态属性";
String addr = "父类非静态属性";
static int m=1;
static {
m=2;
System.out.println(name);
System.out.println("父类静态块");
}
{
System.out.println("父类非静态块");
}
public Person() {
System.out.println("父类构造方法");
}
}
public class Student extends Person {
static String name1 = "子类静态属性";
String addr1 = "子类非静态属性";
static {
System.out.println(name1);
System.out.println("子类静态块");
}
{
System.out.println("子类非静态块");
}
public Student() {
System.out.println("子类构造方法");
}
public static void main(String[] args) {
System.out.println("-------main begin---");
Student st = new Student();
System.out.println("m = " +st.m); //static int m=1在静态代码块上打印m=2,在下打印m=1
System.out.println("-------main end---");
}
}
执行结果: