Practical side of the ability to define a class within an interface in Java?

前端 未结 11 1133
暖寄归人
暖寄归人 2020-12-30 06:32

What would be the practical side of the ability to define a class within an interface in Java:

interface IFoo
{
    class Bar
    {
        void foobar (         


        
相关标签:
11条回答
  • 2020-12-30 07:03

    I can think of another usage than those linked by Eric P: defining a default/no-op implementation of the interface.

    ./alex

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

    Yet another sample — implementation of Null Object Pattern:

    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);
    ...
    
    0 讨论(0)
  • 2020-12-30 07:07

    I think this page explains one example pretty well. You would use it to tightly bind a certain type to an interface.

    Shamelessly ripped off from the above link:

    interface employee{
        class Role{
              public String rolename;
              public int roleId;
         }
        Role getRole();
        // other methods
    }
    

    In the above interface you are binding the Role type strongly to the employee interface(employee.Role).

    0 讨论(0)
  • 2020-12-30 07:11

    Doing this seems to have "Bad design decision" written all over it.

    0 讨论(0)
  • 2020-12-30 07:19

    One use (for better or worse) would be as a workaround for the fact that Java doesn't support static methods in interfaces.

    interface Foo {
        int[] getData();
    
        class _ {
            static int sum(Foo foo) {
                int sum = 0;
                for(int i: foo.getData()) {
                    sum += i;
                }
                return sum;
            }
        }
    }
    

    Then you'd call it with:

    int sum = Foo._.sum(myFoo);
    
    0 讨论(0)
  • 2020-12-30 07:23

    This approach can be used to define many classes in the same file. This has worked well for me in the past where I have many simple implementations of an interface. However, if I were to do this again, I would use an enum which implements an interface which would have been a more elegant solution.

    0 讨论(0)
  • 2020-12-30 07:25

    I guess you could define a class that is used as the return type or parameter type for methods within the interface. Doesn't seem particularly useful. You might as well just define the class separately. The only possible advantage is that it declares the class as "belonging" to the interface in some sense.

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