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

前端 未结 11 1308
暖寄归人
暖寄归人 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: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);
    

提交回复
热议问题