简体   繁体   中英

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.

“匿名内部类可以扩展一个子类或实现一个接口。与非匿名类(内部或其他)不同,匿名内部类不能两者兼有。换句话说,它不能既扩展类又实现接口,也不能它实现了多个接口。”( 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()

For save some keystrokes (for example if the interfaces have a lot of methods) you can use

abstract class Aggregate implements A,B{
}

new MyObject extends Aggregate{
   void foo(){}
   void bar(){}
}

Notice the key is to declare the Aggregate as abstract

Note that you can make a named local class that implements the two interfaces:

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

    A a = new Aggregate();
    B b = new Aggregate();
}

This save you from doing a class-level or top-level class declaration.

The result is called a local class . Local classes declared in instance methods are also inner classes, which means that they can reference the containing object instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM