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

Zsombi picture Zsombi · Jan 23, 2011 · Viewed 6.9k times · Source

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

Answer

aioobe picture aioobe · Nov 24, 2011

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?