java - 在 java 中使用 "final"关键字

标签 java final

<分区>

我遇到过 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 {
  // 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);     
    }
}

关于java - 在 java 中使用 "final"关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33502365/

相关文章:

java - Play 应用程序显示编译单元不在构建路径上

java - Ice4J:Ice State 在 4G 网络上失败

java - 如何在 Java 中执行 rd 命令?

java - playframework 2.3.x 的 msi 安装程序

Java - 静态和最终变量

Groovy 闭包不适用于父类(super class)中的静态最终字段

java - Android 应用程序内部数据存储

java - 在ArrayBlockingQueue中,为什么将final成员字段复制到本地final变量中?

java - 静态最终 int v/s 静态 int