简体   繁体   English

我们可以从具体的 class 创建一个匿名内部 class 吗?

[英]Can we create an anonymous inner class from a concrete class?

There is something surprising in the following code.以下代码中有些令人惊讶的地方。 The ListCell class is not abstract, but we were able to create an anonymous class from it and override its method? ListCell class 不是抽象的,但我们能够从中创建一个匿名的 class 并覆盖它的方法? How is this possible?这怎么可能?

ListCell<TodoItem> listCell = new ListCell<>() {
    @Override
    public void updateIndex(int i) {
        super.updateIndex(i);
    }
};

The concept of anonymous classes (cf. JLS, §15.9.5 ) is simply not related/restricted to abstract classes.匿名类的概念(参见JLS,§15.9.5 )与抽象类无关/不限于抽象类。

new ListCell<>() {} creates an instance of a subclass (with a synthetic name) of ListCell . new ListCell<>() {}创建ListCell的子类(具有合成名称)的实例。 Subclassing is possible unless the parent class is final.除非父 class 是最终的,否则可以进行子类化。 Subclasses can override methods from the parent class unless they're final.子类可以覆盖父类 class 的方法,除非它们是最终的。

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

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