2015-11-03 127 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

请添加评论,说明预计编译错误的位置 –