簡體   English   中英

最終的非靜態數據成員

[英]Final non-static data member

如果不允許兩次初始化finalstatic數據成員,那么如何在下面的示例中將x設置為所需的值?

class Temp6
{
    final int x;

    Temp6()
    {
        System.out.println(this.x);
        this.x=10;
    }

    public static void main(String[]s)
    {
        Temp6 t1 = new Temp6();
        System.out.println(t1.x);
    }
}

Java默認情況下將x的值設置為0 ,那么如何將其更改為10

在Java中標記為final的變量只能初始化一次。

只是簡單地宣稱xfinal int x; 不初始化它。 因此,在Temp6構造函數中分配給x是合法的。 但是,您將無法在構造x之后為x分配其他值。

也就是說,以下是對t1.x的賦值:

public static void main(String[] s) {
  Temp6 t1 = new Temp6();
  t1.x = 11; // ERROR
}

是不合法的。

在類構造函數中初始化最終變量。

public class Blam
{
    private final int qbert;

    public Blam(int qbertValue)
    {
        qbert = qbertValue;
    }
}

在代碼中讀取this.x應該會出錯,因為final變量不會在聲明時初始化。 t1.x應該為10因為x肯定在唯一構造函數的末尾分配。

您必須在構造函數中交換兩行代碼才能進行編譯,那里將是10行。

class Temp {
    int x; // declaration and definition; defaulted to 0
    final int y; // declaration, not initialized
    Temp() {
         System.out.println(x); // prints 0
         x = 1;
         System.out.println(x); // prints 1
         x = 2; // last value, instance.x will give 2

         System.out.println(y); // should be a compiler error: The blank final field y may not have been initialized
         y = 3; // definite assignment, last and only value, instance.y will be 3 whereever used
         System.out.println(y); // prints 3
         y = 4; // compile error: The final field y may already have been assigned
    }
}

我以前從未想過,這里很有趣。 最終字段變量的行為類似於方法中的局部變量 ,必須在使用前對其進行顯式賦值 (確定賦值很難形式化,請參閱JLS參考,但這很合邏輯)。

如果要從外部為x賦值,可以這樣進行:

public class Temp {
    private final int x;
    public Temp(int x) {
        this.x = x;
    }
    public int getX() { return this.x; }

    public static void main(String[] args) {
        Temp temp = new Temp(10);
        System.out.println(temp.getX()); // 10
    }
}

final變量是java常量。 它們應該在類加載之前初始化。

final int x=10;

如果您的最終變量是靜態的,則不必像在聲明本身中給出值一樣,則可以使用-

class Demo {
  static final int x;

   static {
        x = 10;
   }
}

在類加載時,靜態塊僅執行一次

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM