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.
A normal class can implement any number of interfaces but the anonymous inner class can implement only one interface at a time.
Your class can implement more than one interface, so the implements keyword is followed by a comma-separated list of the interfaces implemented by the class.
The syntax of anonymous classes does not allow us to make them implement multiple interfaces.
You can't. The only way to be able to call multiple methods is to assign the anonymous class instance to some variable.
"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)
If you are determined to do this, you could declare a third interface, C:
public interface C extends A, B { }
In this way, you can declare a single anonymous inner class, which is an implementation of C.
A complete example might look like:
public class MyClass { public interface A { void foo(); } public interface B { void bar(); } public interface C extends A, B { void baz(); } public void doIt(C c) { c.foo(); c.bar(); c.baz(); } public static void main(String[] args) { MyClass mc = new MyClass(); mc.doIt(new C() { @Override public void foo() { System.out.println("foo()"); } @Override public void bar() { System.out.println("bar()"); } @Override public void baz() { System.out.println("baz()"); } }); } }
The output of this example is:
foo() bar() baz()
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