让代码自己跑一下就知道了
子类:
package com.figo.study2024.test;
/**
* @ClassName:Test
* @PackageName:com.figo.study2024.test
* @Description:类描述
* @Date:2024/5/13 9:18
* @Author:figo
*/
public class Test extends SuperTest{
static int a;
static String b;
static {
a=100;
b="hello,world";
System.out.println("子类静态代码块执行a="+a+",b="+b);
}
{
a=101;
b="hello,china";
System.out.println("子类非静态代码块执行a="+a+",b="+b);
}
public Test()
{
System.out.println("子类构造函数执行!");
}
public void hello()
{
System.out.println("子类方法执行hi");
}
public static void main(String[] args) {
Test test=new Test();
test.hello();
}
}
父类:
package com.figo.study2024.test;
/**
* @ClassName:SuperTest
* @PackageName:com.figo.study2024.test
* @Description:类描述
* @Date:2024/5/13 9:18
* @Author:figo
*/
public class SuperTest {
static int c;
static String d;
static {
c=100;
d="hello,world";
System.out.println("父类静态代码块执行c="+c+",d="+d);
}
{
c=101;
d="hello,china";
System.out.println("父类非静态代码块执行c="+c+",d="+d);
}
public SuperTest()
{
System.out.println("父类构造函数执行!");
}
}
执行Test中的main方法,执行结果:
父类静态代码块执行c=100,d=hello,world
子类静态代码块执行a=100,b=hello,world
父类非静态代码块执行c=101,d=hello,china
父类构造函数执行!
子类非静态代码块执行a=101,b=hello,china
子类构造函数执行!
子类方法执行hi
一句话,父类的优先执行,静态代码块优先执行,静态代码块>非静态代码块>构造函数>被调用方法。