In there an internal issue why java anonymous classes cannot implement and subclass at the same time? Or is it just because the syntax?
A normal class can implement any number of interfaces but the anonymous inner class can implement only one interface at a time.
You can't. The only way to be able to call multiple methods is to assign the anonymous class instance to some variable.
The syntax of anonymous classes does not allow us to make them implement multiple interfaces.
No, anonymous types cannot implement an interface. We need to create your own type.
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?
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',
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With