When I read about nesting an interface inside of a class, the intention appears to be to encapsulate the abstract behavior of the interface through composition. However, to me it makes more sense to create the interface outside the class, then use a getter/setter and return an instance of the interface type. There must be a benefit that I’m not seeing. Is this simply a matter of “choice”.
Share
If the interface strongly related with some class, it might be reasonable to nest it within the class. For example: SurfaceHolder.Callback which allows a client to receive information about changes to the surface in Android. The Callback interface is nested within the SurfaceHolder, and it is easier to access and find it within that context.
However, for generic interfaces such as Runnable which is implemented by a class whose instances to be executed by a thread, it is completely outside of a class (in the java.lang package for this example). This make more sense because, this interface could be used by any class, not necessarily within a specific context).