这个Java代码如何实例化一个抽象类?
作者:互联网
我正在更改我们的Java类,我注意到以下代码行:
OurClass<OurInterface1> ourClass = new OurClass<OurInterface1>() {};
我对这一行感到奇怪的是,OurClass是一个抽象类 – 这里是OurClass的定义:
public abstract class OurClass<T extends OurInterface1> implements OurInterface2<T>
当我删除行末尾的{}时,Eclipse告诉我无法实例化类型OurClass< OurInterface1>,但当我把{}放回去时,一切正常.
{}如何允许您实例化一个抽象类?
解决方法:
添加{}引入了anonymous inner class的语法.
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的子类.这个类的主体是空的:{}.这个匿名内部类不是抽象的,因此您可以实例化它.
当你删除{}时,编译器认为你直接实例化了一个抽象类OurClass,所以它不允许它.
标签:java,class,syntax,instantiation,abstract 来源: https://codeday.me/bug/20190728/1558873.html