gpt4 book ai didi

java - Thinking in Java 4th Edition——什么是classname.this.method()

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:39:10 24 4
gpt4 key购买 nike

阅读“Thinking in Java 4th Edition”我在第 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(),但这意味着什么?

最佳答案

CoffeeGenerator.this 允许从内部类 CoffeeIterator 访问外部类 CoffeeGenerator

JLS 15.8.4将其描述为合格的 this

Any lexically enclosing instance (§8.1.3) can be referred to by explicitly qualifying the keyword this.

阅读:Inner classes

关于java - Thinking in Java 4th Edition——什么是classname.this.method(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22620813/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com