代码之家  ›  专栏  ›  技术社区  ›  giri

我们能在一个接口内定义一个接口吗?

  •  15
  • giri  · 技术社区  · 14 年前

    我想知道我们能在一个接口中定义一个接口吗? 喜欢

    interface abc {
        void show();
        public interface xyz {
            void read();
        }
    }
    

    这是采访中问的问题。任何实时使用。

    5 回复  |  直到 14 年前
        1
  •  41
  •   Hardik Modha Jayhello    6 年前

    是的,我们能做到。Java中嵌套接口的定义如下:

    嵌套接口是其声明出现在另一个类或接口的主体中的任何接口。顶级接口是不是嵌套接口的接口。

    参考 this 更多。

    进一步…

    一个原因可能是外部接口有一个方法,该方法将回调实现作为参数。在这种情况下,嵌套接口是回调方法必须实现的约定。我看不出在顶层声明回调接口的原因。

    public interface Processor {
       void execute(NotificationListener listener);
    
        interface NotificationListener {
            void processingCompleted();
        }  
    }
    

    Sun网站上关于这个话题的另一篇好文章是 here

    特别是,请注意,在实现接口时, 不需要执行任何 嵌套在中的接口。

        2
  •  7
  •   joe    11 年前

    当然。。查看java.util.map接口的源代码。映射接口包含嵌套的入口接口。

    有趣的是,在源代码中,它只是说

    interface Entry <K,V> {
      ..
    }
    

    但JavaDoc说

    public static interface Map.Entry<K,V>
    

    我想这是因为嵌套接口是隐式的“公共静态”的,即使源代码没有这么说。(但接口内的方法是隐式公共的,不能是静态的,也就是说,接口中只允许实例方法)。

    -DBEDNAR 2013年7月2日

        3
  •  6
  •   user207421    11 年前

    你可以自己测试一下,在大约30秒内得到一个完全确定的、无意见的、无风险的答案。

    相比之下,在论坛上永远等待可能不正确的回答可能不是一种理性的询问方式。

        4
  •  1
  •   Andrew Barber Eric Lafortune    11 年前

    我们在应用程序中使用它, 因此,无意中没有其他人会在项目中的其他地方创建与此服务1相关的新常量。

    示例代码:

    Public interface Service1{
    
      public interface ServiceInter1{
    
       public Interface In{
        Declare your own constants
       }
    
       public Interface Out{
          Declare your own constants
       }
    
     }
    
    }
    
        5
  •  0
  •   Harshal Patil    9 年前

    是的,我们可以定义。

    在地图界面内,定义条目如下。 公共接口图{

    /**
     * Map.Entry is a key/value mapping which is contained in a Map.
     */
    public static interface Entry<K, V> {
        .....some loigic
     }
    }