posts - 51, comments - 17, trackbacks - 0, articles - 9
            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理

          java static

          Posted on 2007-04-08 20:12 chenweicai 閱讀(133) 評論(0)  編輯  收藏

          1.靜態變量

          public class Chinese {

           static String country = "中國";
           
           String name;
           int age;
           
           void singOurCountry(){
            System.out.println("啊, 親愛的" + country);
           }
          }

           public static void main(String[] args) {

            System.out.println("Chinese country is :" + Chinese.country);//類.成員
            Chinese ch1 = new Chinese();
            System.out.println("Chinese country is :" + ch1.country);//對象.成員
                  ch1.singOurCountry();
           }


          注:1. 不能把任何方法內的變量聲明為static類型
                  2. 靜態成員變量為該類的各個實例所共享,所以在內存中該變量只有一份,
                      經常用來計數統計
          如:
          class A{
               private static int  count = 0;

                public A(){
                    count = count + 1;  
              }

          public void finalize(){//在垃圾回收時,finalize方法被調用
                 count = count - 1;
              }
          }


          2.靜態方法
          public class Chinese {

           //在靜態方法里,只能直接調用同類中的其他靜態成員,不能直接訪問類中的非靜態成員和方法
           //因為對如非靜態成員和方法,需先創建類的實例對象后才可使用。
           //靜態方法不能使用關鍵字this和super,道理同上
           //main方法是靜態方法,不能直接訪問該類中的非靜態成員,必須先創建該類的一個實例
           static void sing(){
            System.out.println("啊...");
           }
           
           void singOurCountry(){
            sing();//類中的成員方法可以直接訪問靜態成員方法
            System.out.println("啊...祖國...");
           }
          }

           public static void main(String[] args) {

            Chinese.sing();//類.方法
            
            Chinese ch1 = new Chinese();
            ch1.sing();//對象名.方法
            ch1.singOurCountry();
           }


          3. 靜態代碼塊
          public class StaticCode {

           static String country;
           
           static{
            country = "Chine";
            System.out.println("Static code is loading...");
           }
          }

          public class TestStatic {

           static{
            System.out.println("TestStatic code is loading..."); 
           }
           
           public static void main(String[] args){
            System.out.println("begin executing main method...");
            //類中的靜態代碼將會自動執行,盡管產生了類StaticCode的兩個實例對象,
            //但其中的靜態代碼塊只被執行了一次。同時也反過來說明:類是在第一次被使用時
            //才被加載,而不是在程序啟動時就加載程序中所有可能要用到的類
            new StaticCode();
            new StaticCode();
           }
           
          }




          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 商洛市| 西乌珠穆沁旗| 成武县| 义乌市| 临武县| 长丰县| 阜宁县| 项城市| 承德县| 宜黄县| 天峨县| 蒲江县| 连州市| 东兴市| 桐柏县| 政和县| 虹口区| 松原市| 南涧| 海南省| 沅陵县| 辽阳市| 普兰店市| 桐乡市| 宁河县| 盘山县| 临高县| 淳安县| 工布江达县| 广东省| 巴马| 中方县| 麟游县| 灯塔市| 宜丰县| 乐业县| 泾阳县| 科尔| 宝坻区| 遵化市| 丰宁|