狼人
          走在SCJP的路上
          posts - 12,  comments - 14,  trackbacks - 0

           

           1public class IntReference {
           2    private int level = 0;
           3    
           4    public static void main(String[] args) {
           5        IntReference ag1 = new IntReference();
           6        IntReference ag2 = new IntReference();
           7        ag1.level = 1;
           8        ag2.level = 2;
           9        System.out.println("A:ag1.level = " + ag1.level);
          10        System.out.println("A:ag2.level = " + ag2.level);
          11    //    ag1 = ag2;
          12    /** 上面這種寫法,原本ag1包含的對對象的引用,是指向一個值為1的對象。
          13     *  在對t1賦值的時候,這個引用被覆蓋,也就是丟失了而那個不再被引用的
          14     *  對象會由"垃圾回收器"自動清理。為此為了避免這種現象,應該用下面這
          15     *  種寫法,這樣可以保持兩個對象彼此獨立,而不是將ag1、ag2捆綁到相同
          16     *  的對象上。*/

          17        ag1.level = ag2.level;
          18        System.out.println("B:ag1.level = " + ag1.level);
          19        System.out.println("B:ag2.level = " + ag2.level);
          20        ag1.level = 3;
          21        System.out.println("C:ag1.level = " + ag1.level);
          22        System.out.println("C:ag2.level = " + ag2.level);
          23    }

          24}

           1public class ObjectReference {
           2    private char charA = 'a';
           3    
           4    public void f(ObjectReference b) {
           5        b.charA = 'b';
           6    }

           7    
           8    public static void main(String[] args) {
           9        ObjectReference objReference = new ObjectReference();
          10        objReference.charA = 'c';
          11    //    A:objReference.charA = c
          12        System.out.println("A:objReference.charA = " + objReference.charA);
          13    /**    傳遞一個引用,而不是f(objReference)要在其作用域內復制其參數ObjectReference b的一個副本。*/
          14        objReference.f(objReference);
          15    //  B:objReference.charA = b    
          16        System.out.println("B:objReference.charA = " + objReference.charA);
          17    }

          18}
          posted on 2009-01-03 17:37 狼人 閱讀(256) 評論(0)  編輯  收藏 所屬分類: Java

          <2009年1月>
          28293031123
          45678910
          11121314151617
          18192021222324
          25262728293031
          1234567

          常用鏈接

          留言簿

          隨筆分類

          隨筆檔案

          文章檔案

          搜索

          •  

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 南开区| 淳安县| 广宁县| 文山县| 平凉市| 郎溪县| 陆川县| 木里| 扬州市| 岳西县| 云南省| 肇州县| 呼玛县| 乌海市| 双柏县| 桑日县| 鲁山县| 利津县| 大同县| 白城市| 苗栗县| 务川| 白玉县| 西平县| 吉林省| 定西市| 德庆县| 外汇| 年辖:市辖区| 台东县| 石首市| 清涧县| 二连浩特市| 外汇| 淮安市| 黄梅县| 临沧市| 同仁县| 霍城县| 澜沧| 罗平县|