我们为什么要在类中声明一个接口? [英] Why should we declare an interface inside a class?

查看:239
本文介绍了我们为什么要在类中声明一个接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Why should we declare an interface inside a class in Java?

例如:

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.

在JDK中,最重要的例子是 Map.Entry 内部接口,在地图中定义接口并通过各种方式实现 HashMap LinkedHashMap 等......

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

当然, Map.Entry 需要声明为 public 为了方便使用在代码所在的任何地方迭代地图。

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

这篇关于我们为什么要在类中声明一个接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆