How does this java code instantiate an abstract class?

I'm changing our Java class, and I notice the following line of code:

OurClass<OurInterface1> ourClass = new OurClass<OurInterface1>() {};

What I find strange about this line is that ourclass is an abstract class - here is the definition of ourclass:

public abstract class OurClass<T extends OurInterface1> implements OurInterface2<T>

When I delete {} at the end of the line, eclipse tells me that the type ourclass < ourinterface1 > cannot be instantiated, but when I put {} back, everything is normal

How does {} allow you to instantiate an abstract class?

Solution

Add {} to introduce the syntax of anonymous inner class

You are declaring an anonymous inner class, which is a subclass of ourclass The body of this class is empty: {} This anonymous inner class is not abstract, so you can instantiate it

When you delete {}, the compiler thinks you directly instantiate an abstract class ourclass, so it does not allow it

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>