Implement two interfaces in an anonymous class

后端 未结 4 1822
南方客
南方客 2021-02-06 21:08

I have two interfaces:

interface A {
    void foo();
}

interface B {
    void bar();
}

I am able to create anonymous instances of classes impl

4条回答
  •  庸人自扰
    2021-02-06 21:28

    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()
    

提交回复
热议问题