3

我们是否可以在接口中拥有一个类,该类在其中实现了接口的不同方法。我在这里怀疑为什么 Java 允许在接口中编写内部类以及我们可以在哪里使用它。

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

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

4 回答 4

5

您可以在接口内定义一个类。在接口内部,内部类是隐式的public static

JLS 第 9.1.4 节

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

JLS 第 9.5 节

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

接口中的成员类型声明是隐式的 static 和 public。允许冗余指定这些修饰符中的一个或两个。

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

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

interface Hello {
    class HelloInner {

    }
}

将生成两个类文件:

Hello.class
Hello$HelloInner.class
于 2013-08-19T18:39:01.583 回答
2
Can we have a class inside an interface which has different methods of the interface implemented in it.

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

如果你 class在 an 中写 innerinterface它总是public and static.

相当于

public interface StrangeInterface
    {
 public static class Inner{

}

和里面的变量interface也是显式的public static variables

于 2013-08-19T18:37:48.157 回答
1

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

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

于 2013-08-19T18:43:22.763 回答
0

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

写你的代码

    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();
    }
}
于 2018-07-18T19:19:45.433 回答