Java:抽象类包含奇怪初始化的自类静态字段
在 Eclipse CDT 插件中,我发现了这种初始化抽象类字段的不寻常方式。
ALL 引用的字段是该类本身的一个类。
abstract public class IndexFilter {
public static final IndexFilter ALL = new IndexFilter() {};
....
}
new IndexFilter() {}; 的作用是什么? ?
你能解释一下这个初始化吗?
In the Eclipse CDT plugin, I found this unusual way of initializing a field of an abstract class.
The field ALL refers is a class of the class itself.
abstract public class IndexFilter {
public static final IndexFilter ALL = new IndexFilter() {};
....
}
What is the role of new IndexFilter() {}; ?
Can you explain this initialization?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
IndexFilter() {};
创建IndexFilter
的“匿名子类”。由于大括号是空的,子类不会覆盖基类中的任何内容。由于 IndexFilter 是抽象的,它不能直接实例化,因此需要一个子类。IndexFilter() {};
creates an "anonymous subclass" ofIndexFilter
. Since the braces are empty, the subclass does not override anything in the base class. Since IndexFilter is abstract, it cannot be instantiated directly, hence why a subclass is required.我认为你所说的“不寻常”是因为它是一个匿名内部(或更准确地说,嵌套)类。
new IndexFilter() {}
在一个表达式中创建IndexFilter
的具体子类以及该子类的实例。显然,这是可能的,因为IndexFilter
没有任何抽象方法。如果有,您必须在花括号之间为它们提供一个实现。I think what you refer to as "unusual" is the fact that it's an anonymous inner (or to be more precise, nested) class.
new IndexFilter() {}
creates a concrete subclass ofIndexFilter
and an instance of that subclass in one expression. Obviously this is only possible becauseIndexFilter
hasn't got any abstract methods. If it had, you'd have to provide an implementation for them between the curly braces.这意味着过滤器将传递所有信息。通常,过滤器意味着过滤一些条目。 ALL 是这里的特例。您还可以将 NONE 视为特殊情况,它将过滤掉所有信息。
示例:
使用这种模式的其他类是 Integer,它具有 MAX_VALUE 和 MIN_VALUE。
It means that the filter will pass all information. Normally, filter meant to filter some entries. ALL is the special case here. You can also think of NONE as special case which will filter out all information.
Example:
Other class that uses such pattern is Integer which has MAX_VALUE and MIN_VALUE.
看起来它只是一个易于访问的 IndexFilter 实例,不会覆盖任何内容。
Looks like it's meant to just be a single easily-accessible instance of
IndexFilter
which doesn't override anything.