Code Poet Code Poet - 5 months ago 18
Android Question

Implement two interfaces in an anonymous class

I have two interfaces:

interface A {
void foo();
}

interface B {
void bar();
}


I am able to create anonymous instances of classes implementing either of these interfaces like so:

new A() {
void foo() {}
}


or:

new B() {
void bar() {}
}


I want to create an anonymous class that implements both interfaces. Something like (the fictitious):

new A implements B {
void foo() {}
void bar() {}
}


This obviously gives a compile error: "B cannot be resolved to a type".

The workaround is quite simple:

class Aggregate implements A, B {
void foo() {}
void bar() {}
}


I then use
Aggregate
where ever I would have used the anonymous class.

I was wondering if it is even legal for an anonymous class to implement two interfaces.

dbf dbf
Answer Source

"An anonymous inner class can extend one subclass or implement one interface. Unlike non-anonymous classes (inner or otherwise), an anonymous inner class cannot do both. In other words, it cannot both extend a class and implement an interface, nor can it implement more than one interface. " (http://scjp.wikidot.com/nested-classes)