在 java 中使用 "final" 关键字

using "final" keyword in java

我遇到了 final 关键字,它显然锁定了一个值,因此以后无法更改。但是当我尝试使用它时,变量 x 仍然被更改。我哪里出错了吗?

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);
  }

}

您应该将代码更改为:

public class Class {

    private final int x;

    public Class() {
       x = 123;
    }

    ...
}

与其声明三次,不如声明一次。 事实上 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);

  }

}
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);     
    }
}