OurClass<OurInterface1> ourClass = new OurClass<OurInterface1>() {};
我对这一行感到奇怪的是,OurClass是一个抽象类 – 这里是OurClass的定义:
public abstract class OurClass<T extends OurInterface1> implements OurInterface2<T>
当我删除行末尾的{}时,Eclipse告诉我无法实例化类型OurClass< OurInterface1>,但当我把{}放回去时,一切正常.
{}如何允许您实例化一个抽象类?
解决方法
The anonymous class expression consists of the following:
The new operator
The name of an interface to implement or a class to extend. In this example,the anonymous class is implementing the interface HelloWorld.
Parentheses that contain the arguments to a constructor,just like a normal class instance creation expression. Note: When you implement an interface,there is no constructor,so you use an empty pair of parentheses,as in this example.
A body,which is a class declaration body. More specifically,in the body,method declarations are allowed but statements are not.
您正在声明一个匿名内部类,它是OurClass的子类.这个类的主体是空的:{}.这个匿名内部类不是抽象的,因此您可以实例化它.