Java 静态代码块、代码块、构造方法和多态继承的代码执行顺序
- 测试代码
import lombok.Getter;
public class ExecutionOrder {
{
System.out.println("ExecutionOrder code 0");
}
static {
System.out.println("ExecutionOrder static code");
}
{
System.out.println("ExecutionOrder code 2");
}
public ExecutionOrder() {
System.out.println("ExecutionOrder construction");
}
public static void main(String[] args) {
AbsBase child = new Child();
child.func();
System.out.println("result: k = " + child.getK());
System.out.println("result: i, j, k = " + child.i + " - " + child.j + " - " + child.k);
}
}
abstract class AbsBase {
int i = 1;
int j = 2;
@Getter
int k;
{
System.out.println("AbsBase code 0");
}
static {
System.out.println("AbsBase static code");
}
{
System.out.println("AbsBase code 2");
}
public AbsBase() {
System.out.println("AbsBase construction");
}
abstract void func();
}
class Parent extends AbsBase {
int i = 3;
int j = 4;
@Getter
int k = -1;
{
System.out.println("Parent code 0");
}
static {
System.out.println("Parent static code");
}
{
System.out.println("Parent code 1");
}
Parent() {
System.out.println("Parent construction");
}
@Override
public void func() {
System.out.println("Parent this.getK(): " + this.getK());
System.out.println("Parent super.getK(): " + super.getK());
System.out.println("Parent.func(): " + i + " - " + j + " - " + k);
}
}
class Child extends Parent {
int i = 5;
int j = 6;
@Getter
int k = -2;
{
System.out.println("Child code 0");
}
static {
System.out.println("Child static code");
}
{
System.out.println("Child code 1");
}
Child() {
System.out.println("Child construction");
}
@Override
public void func() {
System.out.println("Child this.getK(): " + this.getK());
System.out.println("Child super.getK(): " + super.getK());
System.out.println("Child.func(): " + i + " - " + j + " - " + k);
}
}
- 执行结果
ExecutionOrder static code
AbsBase static code
Parent static code
Child static code
AbsBase code 0
AbsBase code 2
AbsBase construction
Parent code 0
Parent code 1
Parent construction
Child code 0
Child code 1
Child construction
Child this.getK(): -2
Child super.getK(): -1
Child.func(): 5 - 6 - -2
result: k = -2
result: i, j, k = 1 - 2 - 0
Process finished with exit code 0
作 者:月 暮
出 处:https://www.cnblogs.com/AardWolf/
特此声明:欢迎园子的大大们指正错误,共同进步。如有问题或建议,也请各位大佬多多赐教!如果您觉得文章对您有帮助,可以点击文章右下角【推荐】一下。
版权声明:本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。
出 处:https://www.cnblogs.com/AardWolf/
特此声明:欢迎园子的大大们指正错误,共同进步。如有问题或建议,也请各位大佬多多赐教!如果您觉得文章对您有帮助,可以点击文章右下角【推荐】一下。
版权声明:本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。