java - "this"在Java中的使用

标签 java this variable-assignment

如果我写下面的类:

public class Example {

      int j;
      int k;

      public Example(int j, int k) {
           j = j;
           k = k;
      }

      public static void main(String[] args) {
           Example exm = new Example(1,2);
           System.out.println(exm.j);
           System.out.println(exm.k);
      }

}

程序可以编译,但是当我运行程序时,main 方法会打印出两个 0。我知道为了说明我想在构造函数中初始化实例变量,我必须这样写:

this.j = j;
this.k = k;

但是如果我不写它,那么在构造函数中(在表达式的左侧和写手侧)评估(或考虑)哪个变量?是参数还是实例变量?有区别吗?

还有其他情况下必须使用 this 吗?

最佳答案

如果你在你的构造函数中没有写“this.variable”,并且如果你在构造函数中有一个与你的字段变量同名的局部变量(包括函数参数),那么局部变量将被视为;局部变量隐藏字段(又名类变量)。

“这个”是唯一的去处:

class OuterClass {
  int field;

  class InnerClass {
    int field;

    void modifyOuterClassField()
    {
      this.field = 10; // Modifies the field variable of "InnerClass"
      OuterClass.this.field = 20; // Modifies the field variable of "OuterClass",
                                  // and this weird syntax is the only way.
    }
  }
}

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

相关文章:

Java:如何计算String[]数组中具有两个相同连续字母的单词的分数

java - 是什么决定Java对象的大小?

java - 删除列表中的重复项

c++ - 使用迭代器和内存位置检查列表中对象的实例

Javascript 变量 - 需要一个变量

java - 如何获取 Google 云端硬盘上已更改文件的 ID

java - 在方法内部使用 "this"(不适用于调用方法、构造函数或变量)

c++ - 为什么我不能给这个 int 赋值?

delphi - Delphi简单数据类型等效

javascript - 为什么使用 setInterval 时对象属性变得未定义