Nested Interfaces

As with classes, you can nest interfaces inside an outer class or another interface. The dynamics are similar to nested classes. However, keep in mind that the classes that ultimately implement these nested interfaces don't have the special access to the class members that a nested class does; instead, they behave just like normally declared classes.

Nested Interfaces in Classes

The syntax for nested interfaces is the same as nested classes, but the results are quite different. Since you are defining only the interface and not the implementation, the user of the interface is free to implement the class any way he wants. A good example of a nested interface implementation is with a special collection. See Example 6-10.

Example 6-10. A nested interface
package oracle.hcj.nested;
public class Inventory {
 public HashSet items;
 public Set getValues( ) {
 return Collections.unmodifiableSet(items);
 }
 public void addItem(final InventoryItem item) {
 items.add(item);
 }
 public Iterator iterator( ) {
 return items.iterator( );
 }
 public void removeElement(final InventoryItem item) {
 items.remove(item);
 }
 public static interface InventoryItem {
 public String getSKU( );
 }
}


In this example, the special collection named Inventory will contain only objects that implement the InventoryItem interface (and therefore define the method getSKU( )). Furthermore, since you don't want to tie down the inventory items to a particular superclass, you make an interface for the inventory items, which allows the user to implement that interface as he sees fit. There are only a few good reasons why you should use inner interfaces. One is to model a composition relationship without restricting the implementation of the composed object. In this case, you would need an inner interface to model the compositional relationship and to let the user of the interface decide on the implementation. Nested interfaces are useful on rare occasions, but most of the time you can achieve the same results simply by declaring the interface in its own file.

Nested Interfaces in Interfaces

It is also possible to nest interfaces within other interfaces, although this is rarely done. The syntax is the same as with nested classes. Although using interfaces nested in other interfaces is less crazy than nesting classes within an interface, it is still pretty weird. Essentially, when you nest an interface inside another interface, you are describing a compositional relationship among interfaces. Conceptually, it is a rather strange thing to do. Therefore, I don't recommend nesting interfaces. Ultimately, nesting classes or interfaces inside other interfaces should probably be blocked by the compiler because using them makes no sense in object-oriented programming. All you can hope to accomplish is to demonstrate some obscure aspects of Java for the admiration of your junior developers. Its practical usefulness is about zero.

      
Comments