Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this Java code instantiate an abstract class?

I am making changes to a Java class of ours, and I noticed the following line of code:

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

What I find strange about that line is that OurClass is an abstract class - here's the definition of OurClass:

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

When I remove the {} at the end of the line, Eclipse tells me Cannot instantiate the type OurClass<OurInterface1>, but when I put the {} back, everything is OK.

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

like image 909
pacoverflow Avatar asked Jan 08 '23 11:01

pacoverflow


1 Answers

Adding the {} introduces the syntax for an 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.

You are declaring an anonymous inner class that subclasses OurClass. The body of this class is empty: {}. This anonymous inner class is not abstract, so you are able to instantiate it.

When you remove the {}, the compiler thinks that you are directly instantiating OurClass, an abstract class, so it disallows it.

like image 149
rgettman Avatar answered Jan 15 '23 06:01

rgettman