chenjinlong

          static和final關(guān)鍵字

          static關(guān)鍵字可用在變量、方法和內(nèi)部類(lèi)中。
          在類(lèi)的定義體中,方法的外部可包含static語(yǔ)句塊,在所屬的類(lèi)被載入時(shí)執(zhí)行一次,用于初始化static屬性,但不能初始化非靜態(tài)變量,類(lèi)變量在整個(gè)類(lèi)中共享。
          如:
          public class Count {
            private int serialNumber;
            public static int counter;

            static {
              System.out.println("static自由塊被執(zhí)行");   //先執(zhí)行靜態(tài)塊
              counter = 1;
            }

            public static int getTotalCount() {
              return counter;
            }
            public Count() {
              counter++;
              serialNumber=counter;
            }
            public static void main(String[] args)
            {
             System.out.println("main() invoked");
             System.out.println("counter = "+Count.counter);
                  Count t=new Count();
                  System.out.println("counter = "+Count.counter+" "+t.serialNumber);
            }
          }

          java.lang.Math是一個(gè)final類(lèi),不可被繼承,final變量是引用變量,則不可以改變它的引用對(duì)象,但可以改變對(duì)象的數(shù)據(jù),final方法不可以被覆蓋,但可以被重載。
          如:
          class Aclass
          {
           int a;
           //構(gòu)造器
           public Aclass()
           {
            a = 100;
           }
           final public void paint(){
            System.out.println("55555555");
           }
           final public void paint(int i){
            System.out.println(i);
           }
           public void setA(int theA)
           {
            a = theA;
           }
           public int getA()
           {
            return a;
           }
          }

          //定義一個(gè)類(lèi)來(lái)測(cè)試
          public class TestFinal
          {       
                 //如果final變量是引用變量,則不可以改變它的引用對(duì)象,但可以改變對(duì)象的數(shù)據(jù)
           final Aclass REF_VAR=new Aclass();
           public static void main(String[] args)
           {
            TestFinal tf = new TestFinal();
            tf.REF_VAR.setA(1);
            System.out.println(tf.REF_VAR.getA());
            tf.REF_VAR.paint();
            tf.REF_VAR.paint(1);
           }
          }

          posted on 2010-08-23 20:09 chenjinlong 閱讀(187) 評(píng)論(0)  編輯  收藏


          只有注冊(cè)用戶(hù)登錄后才能發(fā)表評(píng)論。


          網(wǎng)站導(dǎo)航:
           

          My Links

          Blog Stats

          常用鏈接

          留言簿

          隨筆檔案

          搜索

          最新評(píng)論

          閱讀排行榜

          評(píng)論排行榜

          主站蜘蛛池模板: 呼伦贝尔市| 集贤县| 西吉县| 长葛市| 蓬莱市| 基隆市| 公安县| 平利县| 达拉特旗| 瑞丽市| 天峻县| 定州市| 扎兰屯市| 诸城市| 嘉定区| 鸡东县| 沈阳市| 江永县| 原阳县| 湖口县| 宁乡县| 赣州市| 福海县| 吴堡县| 新郑市| 卓资县| 留坝县| 灵川县| 穆棱市| 南木林县| 长垣县| 金塔县| 汕头市| 威宁| 宜丰县| 轮台县| 绍兴县| 重庆市| 佛教| 津南区| 朝阳市|