在Java中,初始化final變數有多少種方法?


在Java中,**final** 是一個訪問修飾符,可以用於欄位、類和方法。

  • 如果方法是final的,則不能被重寫。
  • 如果變數是final的,則其值不能被修改。
  • 如果類是final的,則不能被繼承。

初始化final變數

一旦宣告final變數,就必須對其進行初始化。您可以初始化final例項變數:

  • 在宣告時。
public final String name = "Raju";
public final int age = 20;
  • 在例項(非靜態)塊中。
{
   this.name = "Raju";
   this.age = 20;
}
  • 在預設建構函式中。
public final String name;
public final int age;
public Student(){
   this.name = "Raju";
   this.age = 20;
}

**注意** - 如果你試圖在其他地方初始化final例項變數,將會產生編譯時錯誤。

示例1:在宣告時

在下面的Java程式中,Student類包含兩個final變數:name和age,我們正在宣告時對其進行初始化:

 線上演示

public class Student {
   public final String name = "Raju";
   public final int age = 20;
   public void display(){
      System.out.println("Name of the Student: "+this.name );
      System.out.println("Age of the Student: "+this.age );
   }
   public static void main(String args[]) {
      new Student().display();
   }
}

輸出

Name of the Student: Raju
Age of the Student: 20

示例2:在例項塊中

在下面的Java程式中,Student類包含兩個final變數:name和age,我們正在例項塊中對其進行初始化:

 線上演示

public class Student {
   public final String name;
   public final int age; {
      this.name = "Raju";
      this.age = 20;
   }
   public void display(){
      System.out.println("Name of the Student: "+this.name );
      System.out.println("Age of the Student: "+this.age );
   }
   public static void main(String args[]) {
      new Student().display();
   }
}

輸出

Name of the Student: Raju
Age of the Student: 20

示例3:在預設建構函式中

在下面的Java程式中,Student類包含兩個final變數:name和age,我們正在預設建構函式中對其進行初始化:

 線上演示

public class Student {
   public final String name;
   public final int age;
   public Student(){
      this.name = "Raju";
      this.age = 20;
   }
   public void display(){
      System.out.println("Name of the Student: "+this.name );
      System.out.println("Age of the Student: "+this.age );
   }
   public static void main(String args[]) {
      new Student().display();
   }
}

輸出

Name of the Student: Raju
Age of the Student: 20

更新於:2020年6月29日

3K+ 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告