Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

interface IFoo
{
    class Bar
    {
        void foobar ()
        {
            System.out.println("foobaring...");
        }
    }
}
like image 221
Vlad Gudim Avatar asked Feb 27 '09 13:02

Vlad Gudim


3 Answers

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);
...
like image 77
alexpopescu Avatar answered Oct 17 '22 05:10

alexpopescu


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

like image 20
Eric Petroelje Avatar answered Oct 17 '22 04:10

Eric Petroelje


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);
like image 39
Adam Crume Avatar answered Oct 17 '22 05:10

Adam Crume