最近在温习java的基础,刷题刷到java的执行顺序,很汗颜,答案回答错了!
题目类似如下:
package com.phpdragon.study.base;public class ExecOrder {Son son = new Son();public static void main(String[] args) {new Grandson();new ExecOrder();//打印出的结果是? } }class Grandson extends Son {static {System.out.println("Grandson static code block");}{System.out.println("Grandson code block");}public Grandson() {System.out.println("Grandson construction method");} }class Son extends Parent {Ohter ohter = new Ohter();static {System.out.println("Son static code block");}{System.out.println("Son code block");}public Son() {System.out.println("Son construction method");} }class Parent {static {System.out.println("Parent static code block");}{System.out.println("Parent code block");}public Parent() {System.out.println("Parent construction method");} }class Ohter {public Ohter() {System.out.println("Ohter construction method");} }
以上代码执行结果是:
Parent static code block
Son static code block
Grandson static code block
Parent code block
Parent construction method
Ohter construction method
Son code block
Son construction method
Grandson code block
Grandson construction method
Parent code block
Parent construction method
Ohter construction method
Son code block
Son construction method
根据结果得出:
java的执行顺序是: 父静态代码块 > 子静态代码块 > 父代属性初始化 > 父代码块 > 父构造函数 > 子代属性初始化 > 子代码块 > 子构造函数。
也就是说最终的执行顺序是:
1.类中所有属性的默认值(一举而成)
2.父类静态属性初始化,静态块,静态方法的声明(按出现顺序执行)
3.子类静态属性初始化,静态块,静态方法的声明 (按出现顺序执行)
4.调用父类的构造方法,
首先父类的非静态成员初始化,构造块,普通方法的声明(按出现顺序执行)
然后父类构造方法。
5.调用子类的构造方法,
首先子类的非静态成员初始化,构造块,普通方法的声明(按出现顺序执行)
然后子类构造方法。
其中静态代码块只执行一次。
以上
ps:
深入了解Java程序执行顺序
java类执行顺序
转载于:.html
本文发布于:2024-02-01 22:43:08,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170679858739907.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |