加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – Interface中的内部类

发布时间:2020-12-15 04:12:54 所属栏目:Java 来源:网络整理
导读:我们可以在接口内部有一个类,该接口具有不同的接口实现方法.我在这里有一个疑问,为什么 Java允许在接口内部编写内部类,以及我们可以在哪里使用它. 在下面的程序中,我在Interface中编写了一个类,并实现了接口的方法.在接口的实现类中,我刚刚调用了内部类方法.
我们可以在接口内部有一个类,该接口具有不同的接口实现方法.我在这里有一个疑问,为什么 Java允许在接口内部编写内部类,以及我们可以在哪里使用它.

在下面的程序中,我在Interface中编写了一个类,并实现了接口的方法.在接口的实现类中,我刚刚调用了内部类方法.

public interface StrangeInterface
    {
      int a=10;int b=5;
      void add();
      void sub();
      class Inner
       {
         void add()
          {
             int c=a+b;
             System.out.println("After Addition:"+c);
          }
         void sub()
         {
             int c=a-b;
             System.out.println("After Subtraction:"+c);
         }
       }
    }   

 abstract public class StrangeInterfaceImpl implements I { 
      public static void main(String args[])
    {
       StrangInterface.Inner i=new StrangeInterface.Inner();
       i.add();
       i.sub();
    }
 }

解决方法

您可以在接口内定义类.在接口内部,内部类是隐式的公共静态.

从JLS Section 9.1.4开始:

The body of an interface may declare members of the interface,that is,fields (§9.3),methods (§9.4),classes (§9.5),and interfaces (§9.5).

从JLS Section 9.5开始:

Interfaces may contain member type declarations (§8.5).

A member type declaration in an interface is implicitly static and public. It is permitted to redundantly specify either or both of these modifiers.

对于在接口或任何其他类中定义的内部类的唯一限制是,您必须使用封闭的成员名称来访问它们.
除此之外,他们之间没有任何关系.编译后,内部类将导致完全不同的类文件.

例如,如果您编译以下源文件:

interface Hello {
    class HelloInner {

    }
}

将生成两个类文件:

Hello.class
Hello$HelloInner.class

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读