繁体   English   中英

在这样的类之后,如何使用“this”?

[英]How is “this” used when it comes after a Class like this?

我不太明白是怎么关键字this是在这种情况下被使用。

private void checkForComodification() {
    // The this I'm concerned about is the first one
    if (CyclicArrayList.this.modCount != this.modCount)
        throw new ConcurrentModificationException();
}

你有时需要内部课程。

this指向内部类实例本身。

MyOuterClass.this指向包含类的实例。

在你的情况下,这是必要的,因为这两个类都有一个modCount属性(并且外部类CyclicArrayList的一个在这里被遮蔽)。

它用于内部类,您希望“外部”作用域中的属性或方法与当前类中的属性或方法具有相同的名称。

默认情况下,'this'关键字引用当前的类范围,如果没有此功能,您将无法访问具有相同名称的外部字段和方法。

public class Outer {
  private String test = "outer;
  private class Inner {
    private String test = "inner";
    public void foo() {
       System.out.println(this.test);       // "inner"
       System.out.println(Outer.this.test); // "outer"
    }
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM