A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© momoxixi 中级黑马   /  2015-11-5 17:51  /  304 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文


  1. public class Sub extends Father {  
  2.     private int b = print("b");// 5  
  3.   
  4.     private static int c = print("c");// 1  
  5.   
  6.     public Sub() {  
  7.         System.out.println("create sub");// 6  
  8.     }  
  9.   
  10.     static {  
  11.         System.out.println("sub begin");// 2  
  12.     }  
  13.   
  14.     public static void main(String[] args) {  
  15.         new Sub();  
  16.     }  
  17.   
  18. }  
  19.   
  20. class Father {  
  21.     private int a = print("a");// 3  
  22.   
  23.     public static int print(String s) {  
  24.         System.out.println(s);  
  25.         System.out.println("father print");  
  26.         return 0;  
  27.     }  
  28.   
  29.     public Father() {// 4  
  30.         System.out.println("create father");  
  31.     }  
  32.   
  33. }  
复制代码
输出:

c
father print
sub begin
a
father print
create father
b
father print
create sub


执行顺序:

1.执行sub里面的static部分,包括属性域与代码块(在访问static属性时,Sub.class被加载)

2.执行father里面的static部分,包括属性域与代码块

3.执行father构造函数

4.执行sub普通属性域

5.执行sub构造函数


注意:这里面sub的static部分,属性域与代码块的执行先后顺序主要有代码的前后决定,其中没有必要联系。

评分

参与人数 1技术分 +1 收起 理由
洋葱头头 + 1

查看全部评分

1 个回复

倒序浏览
不错++++++++++++++
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马