这个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中的String是不可变对象 在面向对象及函数编程语言中,不...
String, StringBuffer 和 StringBuilder 可变性 String不可变...
序列化:把对象转换为字节序列的过程称为对象的序列化. 反序...
先说结论,是对象!可以继续往下看 数组是不是对象 什么是对...
为什么浮点数 float 或 double 运算的时候会有精度丢失的风险...
面试题引入 这里引申出一个经典问题,看下面代码 Integer a ...