局部變量和類變量

注: 註釋掉的代碼都表示錯誤的代碼 因爲Java是面嚮對象語言,全部變量都是類成員,因此Java只有局部變量,沒有全局變量java

<!-- lang: java -->
/*
        * 常量測試類
        * 類常量 和 局部常量
        */
        
class A{
    final int i = 1;		//類常量,在聲明時必須賦值
 //	final int i; i=1;
    static final int x = 1;
    final StringBuffer sbf = new StringBuffer("hello");

public void test1(){
    final int f ;				                //局部常量能夠先聲明後使用,但常量沒有初始值
 //	    System.out.println(f);		//局部常量在使用時必須賦值
     f = 1;
    System.out.println(i);		//1
    final int i = 2;			        //類常量此時將被隱藏
    System.out.println(i);	        //2
     sbf.append("world");
	System.out.println(sbf);    //引用的對象不能夠改變,可是引用的內容能夠改變
     }
 }

      /*
       * 變量測試類
      * 成員變量:聲明在類體中的變量;可分爲:實例變量(不加static) 和 類變量(加static,即靜態變量)
      * 局部變量:不是聲明在類體括號裏面的變量
      */
class B{
    public int x = 1;		//類變量能夠加訪問修飾符
    static int y = 1;
    static int n ;		
    int m ;				//類變量具備初始值,而局部變量沒有初始值,使用時必須賦值
//	m = 1;			//語法規定不能這麼賦值,應該寫成
    {m = 1;}
public void test1(){
       ++x;
       ++y;
        System.out.println("x = "+x+"\n"+"y = "+y);
            System.out.println("m = "+m);
                 System.out.println("n = "+n);
     int z = 100;
     z = 200;		        //從新賦值
     int x = 100;	
     this.y = 200;	
// 類變量被隱藏,但加關鍵字this能夠調用
        System.out.println("z = "+z+" x = "+this.x+" y = "+y);        // z = 200 x = 2 y = 200 	
    }


//局部變量的聲明錯誤
    public static void test2(){
//		static int x = 1;		//局部變量是保存在棧中的,而靜態變量保存於方法區
//		public int x;  		//局部變量不能加任何訪問修飾符
        int i ;
//		int i = 1;		        //同一個範圍內不容許有兩個局部變量命名衝突
            }
}

public class TestMain {
        public static void main(String[] args) {
	    new A().test1();
	    new B().test1();	        //x = 2;y = 2
//不管建立多少個對象,永遠都只分配一個靜態變量,靜態變量在內存中只有一個,JVM加載這個類的過程時會爲靜態變量分配內存
	    new B().test1();	        //x = 2;y = 3 	
            }
}
相關文章
相關標籤/搜索