Implement two interfaces in an anonymous class

后端 未结 4 1819
南方客
南方客 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:20

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

    0 讨论(0)
  • 2021-02-06 21:22

    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.

    0 讨论(0)
  • 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()
    
    0 讨论(0)
  • 2021-02-06 21:42

    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

    0 讨论(0)
提交回复
热议问题