首先创建两个类父类:Person,子类:Student
Person类
/**
*@Date 2024/5/15 16:23
* @Description 主要验证父类的静态final变量、静态变量、静态代码块、变量、普通代码块、构造器
* 子类的静态final变量、静态变量、静态代码块、变量、普通代码块、构造器
* 两者的执行顺序
*/
public class Person {
private final static String finaleStaticParam = finaleStaticParamMeth();
private static String staticParam = staticParamMeth();
private String Param = paramMeth();
private static String finaleStaticParamMeth(){
System.out.println("this is father final static String");
return "father final static String";
}
private static String staticParamMeth(){
System.out.println("this is father static String");
return "father static String";
}
private static String paramMeth(){
System.out.println("this is father String");
return "father String";
}
static {
System.out.println("this is father static block");
}
{
System.out.println("this is father block");
}
public Person() {
System.out.println("this is father constructor");
}
}
Student类
public class Student extends Person {
private final static String finaleStaticParam = finaleStaticParamMeth();
private static String staticParam = staticParamMeth();
private String Param = paramMeth();
private static String finaleStaticParamMeth(){
System.out.println("this is final static String");
return "final static String";
}
private static String staticParamMeth(){
System.out.println("this is static String");
return "static String";
}
private static String paramMeth(){
System.out.println("this is String");
return "String";
}
static {
System.out.println("this is static block");
}
{
System.out.println("this is block");
}
public Student() {
System.out.println("this is constructor");
}
public String result(){
System.out.println("finish");
return "finish";
}
public static void main(String[] args) {
Student student = new Student();
student.result();
}
}
最终执行结果:
this is father final static String
this is father static String
this is father static block
this is final static String
this is static String
this is static block
this is father String
this is father block
this is father constructor
this is String
this is block
this is constructor
finish
最终结果顺序:
父类final静态变量–>父类静态变量–>父类静态代码块–>子类final静态变量–>子类静态变量–>子类静态代码块–>父类变量–>父类代码块–>父类构造器–>子类变量–>子类代码块–>子类构造器
资料:
https://blog.youkuaiyun.com/weixin_34508682/article/details/114423908
https://blog.youkuaiyun.com/weixin_37968613/article/details/114597004