Private Interfaces

interface, java

Solution

The `private` keyword means "anyone in the same class":

public class Foo {

   private interface X {...}
   private class X1 implements X {...}
}

This means all classes declared inside of `Foo` can use the interface `Foo.X`.

A common use case for this is the command pattern where `Foo` accepts, say, strings and converts them into internal command objects which all implement the same interface.

If you add a second class `Bar` to the file `Foo.java`, then it can't see `Foo.X`.

Problem

How can we use the methods of a private interface in our code? Abstract classes are something which cannot be instantiated. So, if we need to use methods of abstract class, we can inherit them and use their methods. But, when we talk about interfaces, we need to implement them to use their methods.

Original source