笔试题中经常遇到的考察对static代码块的理解

Posted on 2011-05-27 21:12 居健 阅读(199) 评论(0)  编辑  收藏 所属分类: Java
近日来忙于找工作,虽是技术菜鸟,但特别希望能做与开发类的工作,因而笔试题也相对见了不少,几乎每一家公司都会在考察java时出上一道与static代码块有关的题。这里列出一道经常见到的题(有时候许久不复习,还是会记忆模糊- -!)
代码1 SonClass.java
 1 /**
 2  * Created by IntelliJ IDEA.
 3  * User: solo
 4  * Date: 11-5-20
 5  * Time: 下午7:29
 6  * To change this template use File | Settings | File Templates.
 7  */
 8 public class SonClass extends FatherCLass
 9 {
10     private  String sonName = "son";
11     static
12     {
13         System.out.println("It's the son static field");
14     }
15     public static void main(String[] args)
16     {
17         SonClass sonClass = new SonClass();
18         System.out.println("SonClass has been created");
19     }
20 }
21 class FatherCLass
22 {
23 
24     private String fatherName = getFatherName();
25     static
26     {
27         System.out.println("It's the first father static field");
28     }
29     static
30     {
31         System.out.println("It's the second father static field");
32     }
33     private static  String getFatherName()
34     {
35         System.out.println("initialize the field:fatherName");
36         return "BaBa";
37     }
38     public FatherCLass()
39     {
40         System.out.println("FatherClass has been created");
41     }
42 }
43 
当然了,题目一般就是要求写出程序的输出。

这里主要涉及到三个主要的问题:
1.static代码块初始化的顺序
2.子类继承父类,在实例化时对父类构造函数的调用
3.父类中fatherName什么时候被初始化

我的理解如下:
1.static代码块的初始化是在类编译期完成的,其执行顺序按照在类中出现的顺序依次执行。因此首先输出的应当是父类中的static块,其次是子类中的static块
2.子类在实例化时,会调用父类构造函数,因此父类构造函数中的out一句会被执行
3.在初始化时,变量先于构造函数
因此,综上,整个程序的输出次序应当是:
父类static块--->子类static块--->父类变量--->父类构造函数--->子类构造函数

实际输出结果如下:
It's the first father static field
It's the second father static field
It's the son static field
initialize the field:fatherName
FatherClass has been created
SonClass has been created

ps:若文中有什么错误,欢迎批评指正。

只有注册用户登录后才能发表评论。


网站导航:
 

posts - 0, comments - 0, trackbacks - 0, articles - 1

Copyright © 居健