首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在java中使用"final“关键字

在java中使用"final“关键字
EN

Stack Overflow用户
提问于 2015-11-03 15:04:00
回答 3查看 109关注 0票数 1

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

代码语言:javascript
复制
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);
  }

}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-11-03 15:17:26

代码语言:javascript
复制
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);
  }
}

现在让我们看看我们是如何实际创建最后一个变量的:

代码语言:javascript
复制
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);     
    }
}
票数 3
EN

Stack Overflow用户

发布于 2015-11-03 15:05:39

您应该将代码更改为:

代码语言:javascript
复制
public class Class {

    private final int x;

    public Class() {
       x = 123;
    }

    ...
}
票数 2
EN

Stack Overflow用户

发布于 2015-11-03 15:07:59

你不应该声明三次,而应该声明一次。事实上,sampleMethod2()不是必需的

代码语言:javascript
复制
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);

  }

}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33502365

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档