为什么我们要在类中声明一个接口?

323 阅读2分钟

类中是可以声明一个接口的,但是我不理解的是在类中声明一个接口有什么意义?我上网查了很多文章,感觉回答的强差人意。最后转向Stack Overflow,这里附上原文链接 -- Why should we declare an interface inside a class?

下面内容就是摘自上述问题,在此记录一下

类中是可以声明一个接口的,例子如下:

public class GenericModelLinker implements IModelLinker {

  private static final Logger LOG =LoggerFactory.getLogger(GenericModelLinker.class);
  private String joinAsPropertyField;
  private boolean joinAsListEntry;
  private boolean clearList;
  private List<Link> joins;

  //instead of a scalar property
  private String uniqueProperty;

  public interface Link {

    Object getProperty(IAdaptable n);

    void setProperty(IAdaptable n, Object value);

  }
}

回答如下:

When you want to gather some fields in an object in order to emphasize a concept, you could either create an external class, or an internal (called either nested (static ones) or inner).

If you want to emphasize the fact that this cooperative class makes strictly no sense (has no use) outside the original object use, you could make it nested/inner.

Thus, when dealing with some hierarchy, you can describe a "nested" interface, which will be implemented by the wrapping class's subclasses.

In the JDK, the most significant example would be Map.Entry inner interface, defined within Map interface and implemented by various ways by HashMap, LinkedHashMap etc...

And of course, Map.Entry needed to be declared as public in order to be accessible while iterating the map wherever the code is.

翻译如下:

当你想要聚集一个对象的一些方面去强调一个概念,你既可以创建一个外部类,也可以创建一个内部类。

如果你想要强调一个事实,一个协作类在离开了原来对象的使用是没有意义的,你可以让这个类成为一个内部类。

在JDK中,最具有代表性的例子是 定义在 Map 接口中的 Map.Entry 内部接口,其被各种方式实现,例如:HashMap ,LinkedHashMap

当然,Map.Entry需要被声明为public,以便在迭代 Map 的时候,无论代码在何处都能被访问到。

若有翻译不好或不当之处,欢迎指出。另外对于回答的最后一点,我就感到有一些奇怪,因为在JDK源码中,我发现 Map.Entry 没有被 public 修饰啊。不过这个回答还是很好的解答了我的疑惑。

这里总结一下,在类中声明一个内部接口或内部类,是对于类一部分的抽象。这个内部接口或内部类与类是紧密联系的,单独使用是不存在意义的。

最后再提出一个问题,当我们要抽象出对象的一部分来强调一个概念时,在类中声明一个接口,还是一个内部类呢?具体一点就是Map.Entry为什么是接口,而不是内部类呢?