Java编程思想第四版 - classname.this.method()是什么?

3

我发现在《Java编程思想》第四版的第14章中有这个例子:

public class CoffeeGenerator
implements Generator<Coffee>, Iterable<Coffee> {
  private Class[] types = { Latte.class, Mocha.class,
    Cappuccino.class, Americano.class, Breve.class, };
  private static Random rand = new Random(47);
  public CoffeeGenerator() {}
  private int size = 0;
  public CoffeeGenerator(int sz) { size = sz; } 
  public Coffee next() {
    try {
      return (Coffee)
        types[rand.nextInt(types.length)].newInstance();
    } catch(Exception e) {
      throw new RuntimeException(e);
    }
  }
  class CoffeeIterator implements Iterator<Coffee> {
    int count = size;
    public boolean hasNext() { return count > 0; }
    public Coffee next() {
      count--;
      return CoffeeGenerator.this.next();
    }
    public void remove() {
      throw new UnsupportedOperationException();
    }
  };    
  public Iterator<Coffee> iterator() {
    return new CoffeeIterator();
  }
}

我注意到我从未遇到过这种结构:

return CoffeeGenerator.this.next();

这是什么意思?我知道 ClassName.class.Method(),但这是什么意思?

这本书没有解释吗? - Ismail Badawi
没看到...可能我错过了。我会在接下来的10分钟内试着找到它... - RussianVodka
4个回答

7
CoffeeGenerator.this允许从内部类CoffeeIterator中访问外部类CoffeeGeneratorJLS 15.8.4将其描述为限定的this。任何词法封闭的实例(§8.1.3)都可以通过显式限定关键字this来引用。详情请参阅:内部类

谢谢!也许我只是在书中跳过了这一页... :) 祝好运! - RussianVodka

2

CoffeeIterator类是CoffeeGenerator的内部类,
CoffeeGenerator.this是对外部类this的引用。
内部类的对象有一个包装/外部对象,这是一种引用该包装/外部对象的方式。


2

CoffeeIterator是一个内部类。这意味着每当创建CoffeeIterator的新实例时,它必须与外部类CoffeeGenerator的一个实例(对象)相关联。CoffeeGenerator.this表示对其“所属”的外部类对象的引用。

相比之下,如果使用static关键字声明了CoffeeIterator,则它将成为嵌套类;它可以访问CoffeeGenerator的静态成员和方法(甚至是私有成员),但它不与任何CoffeeGenerator的实例连接。在这种情况下,CoffeeGenerator.this是非法的。


0

您需要使用 CoffeeGenerator 来提供对外部类的访问,this 表示当前对象,next() 是对该对象调用的方法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接