java 代码块顺序
2021-01-13 本文已影响0人
晏雪峤_美杜莎
java 代码块的执行顺序:
静态变量 > 非静态变量
静态变量 > 静态代码块 > 非静态代码块
父构造 > 子构造
父静态变量 > 父静态代码块 >子静态变量 > 子静态代码块 > 父非静态代码块 > 父构造 > 子非静态代码块 > 子构造.
静态代码块仅仅执行一次, 非静态代码块可以执行多次。
public class TestCodeBlockFather {
{
System.out.println("TestCodeBlockFather code block construct...");
}
static {
System.out.println(" static TestCodeBlockFather code block construct...");
}
public TestCodeBlockFather() {
System.out.println("father construct...");
}
}
public class TestCodeBlock extends TestCodeBlockFather {
{
System.out.println("before construct...." + staticStr);
}
private static String staticStr = "TestCodeBlock-static var";
private String str = "TestCodeBlock var";
static {
System.out.println("static before construct....2");
}
static {
System.out.println("static before construct....3");
}
public TestCodeBlock() {
System.out.println("construct.." + str);
}
{
System.out.println("after construct ...");
}
public String getTime() {
try{
return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
} finally {
return "lastReturn";
}
}
public static void main(String[] args) {
TestCodeBlock testCodeBlock = new TestCodeBlock();
System.out.println(testCodeBlock.getTime());
new TestCodeBlock();
}
}
结果
static TestCodeBlockFather code block construct...
static before construct....2
static before construct....3
TestCodeBlockFather code block construct...
father construct...
before construct....TestCodeBlock-static var
after construct ...
construct..TestCodeBlock var
lastReturn
TestCodeBlockFather code block construct...
father construct...
before construct....TestCodeBlock-static var
after construct ...
construct..TestCodeBlock var