使用“这个”是指“在Java中 [英] The use of "this" in Java

查看:104
本文介绍了使用“这个”是指“在Java中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我写下面的类:

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

}

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

The program compiles, but when I run the program, the main method will print out two 0s. I know that in order to say that I want to initialize the instance variables in the constructor I have to write:

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

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

But if I don't write it, then which variable is evaluated (or considered) in the constructor (on the left and on the write hand side of the expressions)? Is is the argument or the instance variable? Does it make a difference?

是否还有其他情况需要使用

Are there other cases where the use of this is obligatory?

推荐答案

如果你不在你的构造函数中写this.variable,并且你有一个局部变量(包括函数参数)与构造函数中的字段变量同名,然后考虑局部变量;局部变量会影响字段(也就是类变量)。

If you don't write "this.variable" in your constructor, and if you have a local variable (including the function parameter) with the same name as your field variable in the constructor, then the local variable will be considered; the local variable shadows the field (aka class variable).

this是唯一可行的地方:

One place where "this" is the only way to go:

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中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆