Implement two interfaces in an anonymous class

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

提交回复
热议问题