在Java中用接口定义类的能力的实用方面?

Vla*_*dim 12 java interface inner-classes

在Java中用接口定义类的能力的实际方面是什么:

interface IFoo
{
    class Bar
    {
        void foobar ()
        {
            System.out.println("foobaring...");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 18

我可以想到另一种用法,而不是Eric P链接的用法:定义接口的默认/无操作实现.

./alex

interface IEmployee
{

    void workHard ();  
    void procrastinate ();

    class DefaultEmployee implements IEmployee 
    {
        void workHard () { procrastinate(); };
        void procrastinate () {};
    }

}
Run Code Online (Sandbox Code Playgroud)

又一个示例 - Null对象模式的实现:

interface IFoo
{
    void doFoo();
    IFoo NULL_FOO = new NullFoo();

    final class NullFoo implements IFoo
    {
        public void doFoo () {};
        private NullFoo ()  {};
    }
}


...
IFoo foo = IFoo.NULL_FOO;
...
bar.addFooListener (foo);
...
Run Code Online (Sandbox Code Playgroud)


Eri*_*lje 8

我认为这个页面很好地解释了一个例子.您可以使用它将某种类型紧密绑定到接口.

从上面的链接无耻地撕掉:

interface employee{
    class Role{
          public String rolename;
          public int roleId;
     }
    Role getRole();
    // other methods
}
Run Code Online (Sandbox Code Playgroud)

在上面的界面中,您将Role类型强烈绑定到employee接口(employee.Role).


Ada*_*ume 6

一个用途(无论好坏)将作为Java不支持接口中的静态方法这一事实的解决方法.

interface Foo {
    int[] getData();

    class _ {
        static int sum(Foo foo) {
            int sum = 0;
            for(int i: foo.getData()) {
                sum += i;
            }
            return sum;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你打电话给:

int sum = Foo._.sum(myFoo);
Run Code Online (Sandbox Code Playgroud)


cle*_*tus 5

我可以毫不犹豫地说,我从来没有这样做过.我想不出你为什么会这么做的原因.嵌套在类中的类?当然,有很多理由这样做.在这些情况下,我倾向于认为那些内部类是一个实现细节.显然,接口没有实现细节.