码迷,mamicode.com
首页 > 编程语言 > 详细

java初始化顺序

时间:2014-09-17 20:11:42      阅读:247      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   java   ar   div   sp   log   c   

 1 package com.zhangcy.test.init;
 2 
 3 public class Base {
 4     
 5     int str;
 6     static int val1=1;
 7     final int val2=2;
 8     static final int val3 = 3;
 9     
10     public Base(final int s){
11         printStr();
12         System.out.println("pre-base:"+str);
13         str = s;
14         this.printStr();
15         System.out.println("aft-base:"+str);
16     }
17     
18     public Base(){
19         printStr();
20     }
21     
22     private void printStr(){
23         System.out.println("base:"+str);
24         System.out.println("base-val1:"+val1);
25         System.out.println("base-val2:"+val2);
26         System.out.println("base-val3:"+val3);
27     }
28 
29 }
package com.zhangcy.test.init;


public class Derived extends Base {

    int str;
    static int val1=4;
    final int val2=5;
    static final int val3=6;
    
    //Base base = new Base(str);
    //static Base base2 = new Base();
    
    public Derived(int s) {
        super();
        System.out.println("pre-derived:"+str);
        str = s;
        System.out.println("aft-derived:"+str);
        printStr();
    }
    
    public void printStr(){
        System.out.println("derived:"+str);
        System.out.println("derived-val1:"+val1);
        System.out.println("derived-val2:"+val2);
        System.out.println("derived-val3:"+val3);
    }

}
package com.zhangcy.test.init;


public class Basetest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        /*float f = (short)10/10.2f*2;
        double d = (short)10/10*2;*/
        
        Derived derived = new Derived(1);
        //derived = new Derived(10);
        //Derived derived1 = new Derived(20);
         Base base = new Derived(3);
         
        
    }

}

 

1、父类的static变量,逐个上溯,找到最顶级的父类的static变量,依次往下初始化,直至当前类。

2、进入当前类的构造方法,构造方法第一句当然是调用父类的构造方法,依次上溯,找到最顶级的父类,先初始化父类的实例变量,再执行父类构造方法里面的语句,这样依次往下进入当前类,初始化当前类的实例变量,再执行当前类构造方法中调用父类构造方法之后的语句。

 

(未完待续)

 

java初始化顺序

标签:style   blog   color   java   ar   div   sp   log   c   

原文地址:http://www.cnblogs.com/zhangcybb/p/3977781.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!