我们是否可以在接口中拥有一个类,该类在其中实现了接口的不同方法。我在这里怀疑为什么 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();
}
}