JAVA继承关系中父类子类代码执行顺序

时间:2022-08-30 19:34:32

public class FatherClass {

static {
System.out.println("father static code ");
}

public FatherClass(){
System.out.println("father constractor");
}

{
System.out.println("father code");
}

}

public class SubClass extends FatherClass{

static {
System.out.println("sub static code ");
}

public SubClass(){
System.out.println("sub constractor");
}

{
System.out.println("sub code");
}

public static void main(String[] args) {
FatherClass sc = new SubClass();
}

}

执行顺序:
father static code
sub static code
father code
father constractor
sub code
sub constractor

优先级结论:
静态游离块优先级最高,先执行父类静态游离块,再执行子类静态游离块;
普通游离块和构造器次之,先执行父类游离块,和父类构造器,再执行子类游离块,和子类构造器