当前位置: 移动技术网 > IT编程>开发语言>Java > java嵌套接口

java嵌套接口

2019年12月21日  | 移动技术网IT编程  | 我要评论

java嵌套接口

  

package object;

class a {
  //嵌套在类中的接口,可以被private,protected,default和public四种权限修饰 interface b { void f(); } public class bimp implements b { public void f() {} } private class bimp2 implements b { public void f() {} } public interface c { void f(); } class cimp implements c { public void f() {} } private class cimp2 implements c { public void f() {} }
  //私有的嵌套接口,对外不可见,且只能被当前类中的其他内部类所实现 private interface d { void f(); } private class dimp implements d { public void f() {} } public class dimp2 implements d { public void f() {} } public d getd() { return new dimp2(); } private d dref; public void received(d d) { dref = d; dref.f(); } } interface e { interface g { void f(); } // 多余的 "public",接口中所有的成员都是public,其中成员方法都是public abstract(可以有个默认方法),属性都是public static final,接口本身可以是default和public public interface h { void f(); } void g(); // 不能声明为private,理由同上 //! private interface i {} } public class nestinginterfaces { public class bimp implements a.b { public void f() {} } class cimp implements a.c { public void f() {} } //不能实现一个私有接口,除非在接口所属的类内部 //! class dimp implements a.d { //! public void f() {} //! } class eimp implements e { public void g() {} } class egimp implements e.g { public void f() {} } class eimp2 implements e { public void g() {} class eg implements e.g { public void f() {} } } public static void main(string[] args) { a a = new a(); // 无权获取 a.d: //! a.d ad = a.getd(); // a.d类型不能自动向下转换为实现类: //! a.dimp2 di2 = a.getd(); // 更不能调用私有接口的方法 //! a.getd().f(); // only another a can do anything with getd(): a a2 = new a(); a2.received(a.getd());//要使用d 只能把它交给有权使用它的对象 } } ///:~

 总结:

  1. java中接口可以嵌套在类中,也可以嵌套在接口中,处于与成员变量和方法平级的位置;
  2. 不论定义在接口,还是类中,嵌套接口默认强制是 static;
  3. 嵌套在类中的接口,可以被private,protected,default和public四种权限修饰;嵌套在接口中的接口,只能被public修饰;

  4. 在实现接口的过程中,我们不需要实现嵌套在其内部的任何接口。并且private接口是不能在定义它的类之外被实现。

  参考:java编程思想

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网