java-靜態變量,單例模式


static關鍵字. 靜態變量  

static(不在堆里面也不在棧里面, 在數據區(data seg)):

--類名直接 . 出來的變量是靜態變量, 每個類里面的靜態變量只有一份, 是公用的(賦值后每個實例化的類都可使用)
--靜態方法中不可訪問非靜態成員
--靜態變量和靜態方法不需要實例化

package com.hanqi.test;

public calss Dog{
       public static int num;    //靜態屬性      
       //這里還可以寫其他變量
} 
public Dog(){
      num++;
}   
//這里是要get和set一下的.有了返回值,main中調用時就可以如下所示用 點 調用了
 1 //在main 中
 2 packae com. hanqi.test;
 3 public class Main{
 4    public static void main (String[] args){
 5      Dog d1 = new Dog()     System.out.println(Dog.num);      //輸出結果為1    拿類名 . 出來的就是靜態的
 7 
 8      Dog d2 = new Dog()     System.out.println(Dog.num);       //輸出結果為2
10 }    
11 }

這個方法可以作為計數時用.

public void print(){

System.out.println("這是第"+num+"只狗");

}

main中:   

Dog d1 = new Dog();   d1.print();  
Dog d2 = new Dog();   d2.print();  



---end--------------

單例模式 ,
 1 public class Danli {
 2 //構造方法定義成私有的,對外不公開,
 3     //外面沒法通過new一個方法來獲得一個實例
 4     private static Danli helloworld;
 5     private int count;
 6     private Danli() {}  
 7     //對外提供了下面的方法,可以通過類名.下面的方法名
 8     //獲取這個實例
 9     
10     
11     public static Danli Add() {
12         if(helloworld == null) {
13             helloworld = new Danli();
14         }
15         return helloworld;
16     }
17     
18     
19     public int getCount() {
20         return count;
21     }
22 
23     public void setCount(int count) {
24         this.count = count;
25     }
26 }

main中:

public static void main(String[] args) {
        Danli he = Danli.Add();
        Danli he2 = Danli.Add();
        he.setCount(5);
        System.out.println(he2.getCount());
        System.out.println(he2 == he);
                 //==對比的是位置;
        //單例模式無論實例化多少,都指向同一個對象;
    }    
11.20-1文件中  2...









免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM