Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why an Anonymous class can't implement multiple interfaces directly? Simply because of syntax or there is another reason?

Tags:

In there an internal issue why java anonymous classes cannot implement and subclass at the same time? Or is it just because the syntax?

like image 845
Zsombi Avatar asked Jan 23 '11 13:01

Zsombi


People also ask

Can an anonymous inner class implement multiple interfaces?

A normal class can implement any number of interfaces but the anonymous inner class can implement only one interface at a time.

Can anonymous class have multiple methods?

You can't. The only way to be able to call multiple methods is to assign the anonymous class instance to some variable.

Can an anonymous class implement an interface in Java?

The syntax of anonymous classes does not allow us to make them implement multiple interfaces.

Can Anonymous classes implement an interface a yes b no?

No, anonymous types cannot implement an interface. We need to create your own type.


2 Answers

In there an internal issue why java anonymous classes cannot implement and subclass at the same time?

I believe it is 99% due to syntactical reasons. Type parameters even support intersection types (<T extends InterfaceX & InterfaceY>) so I don't think such feature would introduce any contradictions or complications.

An expression like new (InterfaceX & InterfaceY)() { ... } could for instance be compiled into something like

interface InterfaceXandY extends InterfaceX, InterfaceY {} ... new InterfaceXandY() { ... } 

The reason no such feature has been added is most likely because it's a rare use case for which there is a simple workaround.


On a somewhat related note. You can let a lambda implement for instance Serializable by doing

Runnable r = (Runnable & Serializable)() -> System.out.println("Serializable!"); 

See How to serialize a lambda?

like image 88
aioobe Avatar answered Jun 23 '23 17:06

aioobe


solely syntax, so called anonymous classes are 100% normal classes. you can possibly achieve a funky results by using java.lang.reflect.Proxy and InvocationHandler, would be the dirtiest way to do it.

Simpler ways include declaring the class in the method and just adding 'implements',

like image 26
bestsss Avatar answered Jun 23 '23 19:06

bestsss