1. 程式人生 > >Final型別資料的初始化

Final型別資料的初始化

final型別的資料(基本型別和引用型別)分為編譯是確定值,和執行時確定值兩類。都要保證在使用前進行初始化,注意final型別的資料若在定義時沒有顯示初始化,是沒有預設初值的。對於在定義時沒有顯式初始化的,應該在構造方法中進行初始化,這時可以利用不同引數傳遞給它,使得它可以根據具體物件的不同而不同,並且保證在不同的物件中始終唯一。

//FinalDataInitial.java
//Fianl data in the constructor

package com.msn.spaces.bryantd001;

public class FinalDataInitial{

    //編譯時初始化
    private final int finalInt=10; 
    private final float finalFloat=returnFloatValue();
    //執行時初始化
    private final double finalDouble;
    private final String finalStr;

    public FinalDataInitial(){
           System.out.println("Final data are initialized in the constructor without arguments");
           finalDouble=20;
           finalStr="I am a final string initialized in the constructor without argument";
           System.out.println(this);
    }

    public FinalDataInitial(double finalDouble, String finalStr){
          System.out.println("Final data are initialized in the constructor with arguments");
          this.finalDouble=finalDouble;
          this.finalStr=finalStr;
         System.out.println(this);
    }

    public float returnFloatValue(){
          return 1.0f;
    }

    public String toString(){
          return "finalInt = "+finalInt+"/n"
                   +"finalFloat = "+finalFloat+"/n"
                   +"finalDouble = "+finalDouble+"/n"
                   +"finalStr = "+finalStr;
    }

    public static void main(String[] args){
          FinalDataInitial fdiObj=new FinalDataInitial();
          System.out.println();
          FinalDataInitial fdiObj2=new FinalDataInitial(5.0d, new String("I am a final string initialized in the onstructor with argument"));  
    }

}