ITPub博客

首页 > 应用开发 > Java > Java 类初始化顺序

Java 类初始化顺序

原创 Java 作者:self_control 时间:2015-08-16 14:15:06 0 删除 编辑
Java 类初始化顺序为
1、父类静态字段初始化
2、子类静态字段初始化
3、父类普通字段初始化
4、父类构造器执行
5、子类普通字段初始化
6、类构造器执行

点击(此处)折叠或打开

  1. import java.util.Random;

  2. public class InitOrder {
  3.     public static int getInt(String info){
  4.         System.out.println(info);
  5.         Random random = new Random(47);
  6.         return random.nextInt();
  7.     }
  8.     public static void main(String [] args){
  9.         new Son();
  10.         // 关注 Father 的 filed 与 Son 的sonFiled的初始化
  11.     }
  12. }

  13. class Son extends Father{
  14.     private int sonFiled = InitOrder.getInt("子类普通字段初始化");
  15.     private static int sonStaticFiled = InitOrder.getInt("子类静态字段初始化");
  16.     public Son(){
  17.         this.sonFiled = InitOrder.getInt("子类构造器执行");
  18.     }
  19.     public int getSonFiled() {
  20.         return sonFiled;
  21.     }
  22.     public void setSonFiled(int sonFiled) {
  23.         this.sonFiled = sonFiled;
  24.     }
  25.     public static int getSonStaticFiled() {
  26.         return sonStaticFiled;
  27.     }
  28.     public static void setSonStaticFiled(int sonStaticFiled) {
  29.         Son.sonStaticFiled = sonStaticFiled;
  30.     }

  31.     
  32. }
  33. class Father{
  34.     private int filed = InitOrder.getInt("父类普通字段初始化");
  35.     private static int staticFiled = InitOrder.getInt("父类静态字段初始化");
  36.     public Father(){
  37.         this.filed = InitOrder.getInt("父类构造器执行");
  38.     }
  39.     public int getFiled() {
  40.         return filed;
  41.     }
  42.     public void setFiled(int filed) {
  43.         this.filed = filed;
  44.     }
  45.     public static int getStaticFiled() {
  46.         return staticFiled;
  47.     }
  48.     public static void setStaticFiled(int staticFiled) {
  49.         Father.staticFiled = staticFiled;
  50.     }
  51.     
  52. }


来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/30066956/viewspace-1773078/,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2014-12-16

  • 博文量
    49
  • 访问量
    372547