2015-11-03 60 views
1

我遇到了final關鍵字,該關鍵字顯然鎖定在一個值中,因此以後無法更改。但是當我嘗試使用它時,變量x仍然被改變。我在哪裏錯了?在java中使用「final」關鍵字

public class Class { 
    // instance variable 
    private int x; 

    public Class() { 
    // initialise instance variables 
    final int x = 123; 
    } 

    public void sampleMethod() { 
    // trying to change it using final again 
    final int x = 257; 
    System.out.println(x); 

    } 
    public void sampleMethod2() { 
    // trying to change it using without using final 
    x = 999; 
    System.out.println(x); 
    } 

} 
+1

因爲你設置的方法中的局部變量''x'和sampleMethod'你的構造函數是最終的,而不是類變量'x'。 – SomeJavaGuy

+2

因爲在方法中聲明的變量是局部變量,所以你必須爲整個類變量final而不僅僅是構造函數/方法。例如,當構造函數完成時,最終的int x = 123超出範圍。 –

回答

3
public class Class { 
    // instance variable 
    private int x; // <-- This variable is NOT final. 

    public Class() { 
    // initialise instance variables 
    final int x = 123; // <-- This is NOT the instance variable x, but rather hiding this.x with a method local variable called 'x' 
    } 

    public void sampleMethod() { 
    // trying to change it using final again 
    final int x = 257; // <-- This is NOT the instance variable x, but rather hiding this.x with a method local variable called 'x' 
    System.out.println(x); 
    System.out.println(this.x); // see! 

    } 
    public void sampleMethod2() { 
    // trying to change it using without using final 
    x = 999; // This changes this.x, but this.x IS NOT final. 
    System.out.println(x); 
    } 
} 

現在讓我們看看我們如何真正創建一個最終的變量:

public class ClassWithFinalInstanceVariable { 
    private final int x; 
    public ClassWithFinalInstanceVariable() { 
     this.x = 100; // We can set it here as it has not yet been set. 
    } 
    public void doesNotCompileIfUncommented() { 
     // this.x = 1; 
     // If the line above is uncommented then the application would no longer compile. 
    } 

    public void hidesXWithLocalX() { 
     int x = 1; 
     System.out.println(x); 
     System.out.println(this.x);  
    } 
} 
2

您chould更改您的代碼:

public class Class { 

    private final int x; 

    public Class() { 
     x = 123; 
    } 

    ... 
} 
1

,而不用聲明三次,你應該一次聲明它的。 逸岸sampleMethod2()不需要

public class Class { 
    // instance variable 
    private final int x; 

    public Class() { 
    // initialise instance variables 
    x = 123; 
    } 

    public void sampleMethod() { 
    // You will get error here 
    x = 257; 
    System.out.println(x); 

    } 

} 
+0

sampleMethod不會編譯,以及sampleMethod2 –

+0

@AlexanderPogrebnyak OP想知道爲什麼它沒有給出編譯錯誤。所以我刪除了這個聲明,以便引發OP期望的錯誤。在downvoting之前,先閱讀問題 – Rehman

+0

請添加評論,說明預計編譯錯誤的位置 –