加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

这个Java代码如何实例化一个抽象类?

发布时间:2020-12-15 04:27:13 所属栏目:Java 来源:网络整理
导读:我正在更改我们的 Java类,我注意到以下代码行: OurClassOurInterface1 ourClass = new OurClassOurInterface1() {}; 我对这一行感到奇怪的是,OurClass是一个抽象类 – 这里是OurClass的定义: public abstract class OurClassT extends OurInterface1 imple
我正在更改我们的 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,所以它不允许它.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读