接口内的内部类

时间:2013-08-19 18:30:47

标签: java interface interface-implementation

我们可以在接口内部有一个类,该接口具有不同的接口实现方法。我在这里有一个疑问,为什么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();
    }
 }

4 个答案:

答案 0 :(得分:4)

您可以在界面中定义类。在接口内部,内部类隐式public static

来自JLS Section 9.1.4

  

接口的主体可以声明接口的成员,即字段(第9.3节),方法(第9.4节),(第9.5节)和接口(第9.5节)。

来自JLS Section 9.5

  

接口可能包含成员类型声明(第8.5节)。

     

界面中的成员类型声明是隐式静态和公共。允许冗余地指定其中一个或两个修饰符。

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

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

interface Hello {
    class HelloInner {

    }
}

将生成两个类文件:

Hello.class
Hello$HelloInner.class

答案 1 :(得分:2)

Can we have a class inside an interface which has different methods of the interface implemented in it.

恕我直言但接口不是为了这个目的。

如果您在class中写内部interface,则始终为public and static.

相当于

public interface StrangeInterface
    {
 public static class Inner{

}

并且interface内的变量也明确public static variables

答案 2 :(得分:1)

接口可能会提供自己的实现作为默认值。

请注意,除非您声明内部类implements接口,否则除了内部类之外,两者之间没有任何关系。当一个类非常与接口紧密相关时,这本身并不合理,虽然我很怀疑它是一种普遍有用的模式。

答案 3 :(得分:0)

通过在接口内定义一个类来总结“我们可以在哪里使用”:
1.提供接口的默认实现
2.如果接口方法的参数或返回类型为

没有您的代码

    interface StrangeInterface {
    int a = 10;
    int b = 5;

    void add();

    void sub();

    class Inner implements StrangeInterface {
        public void add() {
            int c = a + b;
            System.out.println("After Addition:" + c);
        }

        public void sub() {
            int c = a - b;
            System.out.println("After Subtraction:" + c);
        }
    }
}

class MyTest implements StrangeInterface {

    public void add() {

        System.out.println("My own implementation for add : " + (a +b));
    }

    public void sub() {
        System.out.println("My own implementation for sub : " + (a- b));

    }

}

public class StrangeInterfaceImpl {

    public static void main(String args[]) {
        StrangeInterface.Inner i = new StrangeInterface.Inner(); // calling default implementation
        i.add();
        i.sub();

        MyTest t = new MyTest();   // my own implementation
        t.add();
        t.sub();
    }
}