Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...