“这个”的使用是指“这个”。 爪哇语

发布于 2024-07-13 17:54:33 字数 591 浏览 6 评论 0原文

如果我写下面的类:

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

If I write the following class:

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

}

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

爱你不解释 2024-07-20 17:54:34

就像罗伯特·格兰特所说,“这”就是你如何清楚地表明你引用的是成员变量而不是局部变量。

Just like Robert Grant said, 'this' is how you make it clear that you are referring to a member variable instead of a local variable.

兲鉂ぱ嘚淚 2024-07-20 17:54:34

要回答您的有关此方法的后续问题Srikanth提到的内部类仍然是使用这个的有效示例:(这次使用方法)

public class OuterClass
{
    void f() {System.out.println("Outer f()");};
    class InnerClass {
        void f() {
            System.out.println("Inner f()");
            OuterClass.this.f();
        }
    }
}

您与匿名类

可以通过以下方式引用外部类的方法:

  • MyOuterClass.this.yOuterInstanceMethod(),
  • MyOuterClass.myOuterInstanceMethod(),
  • 或者简单地使用myOuterInstanceMethod()如果没有歧义

To answer your follow-up question about this with method, the inner class mentioned by Srikanth is still a valid example of using this: (with method this time)

public class OuterClass
{
    void f() {System.out.println("Outer f()");};
    class InnerClass {
        void f() {
            System.out.println("Inner f()");
            OuterClass.this.f();
        }
    }
}

You have the same situation with anonymous class:

You can refer to the outer class’s methods by:

  • MyOuterClass.this.yOuterInstanceMethod(),
  • MyOuterClass.myOuterInstanceMethod(),
  • or simply myOuterInstanceMethod() if there is no ambiguity.
水染的天色ゝ 2024-07-20 17:54:34

这并不能完全回答您的问题,但如果您使用 Eclipse,您可能会发现“分配无效”设置很有用。 我确信这也会出现在其他 IDE 中。

This doesn't quite answer your question, but if you use Eclipse you might find "Assignment has no effect" setting useful. I am sure this will be in other IDEs too.

机场等船 2024-07-20 17:54:34

您可能想看看什么是强制显式使用 this/self 指针有什么好处?
虽然正如您所注意到的那样,在 Java 中使用 this 并不是强制的,但我相信它也会对在 Java 中使用 this 的主题有所启发。

You might want to take a look at What is the advantage of having this/self pointer mandatory explicit?
Although using this is not mandatory in Java as you noticed I'm sure it will shed some light on the subject of using this in Java as well.

清风夜微凉 2024-07-20 17:54:34

为了避免这种情况,请使用 IDE(例如 Eclipse),在这种情况下它将生成警告。

另外,除非绝对不可能,否则请将您的字段设为最终字段。 这样做有很多原因(除了这个)。

To avoid this, use an IDE (like Eclipse) and it will generate warnings in this case.

Also, make your fields final unless they absolutely can't be. There are a number of reasons (apart from this one) to do that.

凉世弥音 2024-07-20 17:54:33

如果你的构造函数中没有写“this.variable”,并且构造函数中存在与你的字段变量同名的局部变量(包括函数参数),那么就会考虑局部变量; 局部变量隐藏字段(又名类变量)。

一个地方“this”是唯一的出路:

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.
    }
  }
}

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).

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.
    }
  }
}
热血少△年 2024-07-20 17:54:33

如果您在构造函数中只说了 j ,那么编译器会认为您在这两种情况下都指的是参数。 因此,

j = j;

只需将参数 j 的值分配给参数 j (这是一个毫无意义但仍然有效的语句)。

因此,为了消除歧义,您可以在 this. 前面加上前缀,以明确您指的是具有相同名称的成员变量。

this 的另一个用途是当您需要将对当前对象的引用传递给某个方法时,例如:

someObject.addEventListener(this);

在本例中,您需要将当前对象作为一个整体来引用(而不仅仅是对象的成员)。

If you say just j in your constructor then the compiler will think you mean the argument in both cases. So

j = j;

simply assigns the value of the argument j to the argument j (which is a pretty pointless, but nonetheless valid statement).

So to disambiguate this you can prefix this. to make clear that you mean the member variable with the same name.

The other use of this is when you need to pass a reference to the current object to some method, such as this:

someObject.addEventListener(this);

In this example you need to refer to the current object as a whole (instead of just a member of the object).

撩心不撩汉 2024-07-20 17:54:33

如果你不写这个,那么你将参数分配给它自己; 参数变量隐藏实例变量。

If you don't write this, then you assign the argument to itself; the argument variables shadow the instance variables.

土豪 2024-07-20 17:54:33

当您想要返回对象本身时,

return this;

这很有用。这很有用,因为如果一个类具有例如 Method1() 和 Method2(),两者都返回 this,则允许您在方法中编写类似

object.Method1().Method2()

Also inside a method 的调用,这可能会很有用在调用期间将对象本身传递给另一个函数。

this is useful when you want to return the object itself

return this;

This is useful because if a class has for example Method1() and Method2(), both returning this, you are allowed to write calls like

object.Method1().Method2()

Also inside a method it can be useful to pass the object itself to another function, during a call.

审判长 2024-07-20 17:54:33

另一种有用的方法(尽管很少使用)是将方法参数声明为final:

以下块将不会编译,从而立即提醒您错误:

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

Another useful approach (though seldom used) is to declare method parameters final:

The following block will not compile, thus alerting you to the error immediately:

  public Example(final int j, final int k) {
       j = j;
       k = k;
  }
羁绊已千年 2024-07-20 17:54:33

在构造函数代码中,您将变量分配给它们自己。 'j' 是构造函数参数中指定的 j。 即使它是上面定义的类变量 j,那么您仍然会说“j = j”...即 j 不会在左侧和右侧进行不同的评估。

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

In your constructor code, you are assigning variables to themselves. 'j' is the j specified in the argument for the constructor. Even if it was the class variable j defined above, then you are still saying "j = j" ... i.e. j isn't going to evaluate differently on the left and on the right.

  public Example(int j, int k) {
       this.j = j;
       this.k = k;
  }
月亮是我掰弯的 2024-07-20 17:54:33

您遇到的情况称为变量阴影。 查看Java 中不同类型的变量的概述< /a>.

一般来说:Java 编译器使用它能找到的最接近的变量进行赋值。 在方法中,它首先尝试查找局部变量,然后将搜索焦点扩大到类和实例变量。

我个人认为很好的一个习惯(其他人不喜欢它)是在成员变量前添加 m_ 前缀,并使用大写字母表示不会改变其值的 CONSTANT_VARIABLES。 故意使用变量阴影的代码非常(!)难以调试和使用。

What you are experiencing is called variable shadowing. Have a look at this overview for different kinds of variables in Java.

Generally speaking: The Java compiler uses the nearest variable it can find for an assignment. In a method it will first try to find a local variable and then enlarge the focus of its search to class and instance variables.

One habit I personally find good (others don't like it) is prefixing a member variable with m_ and using uppercase for CONSTANT_VARIABLES that don't change their value. Code where variable shadowing is used on purpose is very(!) difficult to debug and work with.

水溶 2024-07-20 17:54:33

在您的示例中,您将参数分配给自身。

更一般地说:如果您没有在变量前添加作用域,则假定当前作用域 - 这就是您的情况下的函数。 'this.j' 告诉 jre 使用对象范围内的变量 j - 对象的成员变量。

You assign the parameter to itself in your example.

More generally speaking: If you don't prepend a scope to your variable, the current scope is assumed - which is the function in your case. 'this.j' tells the jre to use the variable j within the object scope - the member variable of the object.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文