在书本中看到这样的代码
//定义OutInterface接口
1)public interface OutInterface{
}
//定义OuterClass类
2)public class OuterClass
{
public OutInterface doit(final String x)//********************************这行****************************************
{
class innerClass implements OutInterface
{
innerClass(String s)
{
S = x;
System.out.println(s);
}
}
retrn new InnerClass("doit");
}
}
我就想问下public OutInterface doit(final String x) 为什么接口可以定义方法的?
------解决思路----------------------
public class OuterClass 中定义了一个方法doit(String),返回一个对象OutInterface,由于OutInterface是一个接口,需要返回一个实现该接口的对象,因此定义了class innerClass implements OutInterface,返回了一个new innerClass .
如果我再写一个class叫 Caller即可,注意因为是内部类,Caller只能引用OutInterface实例化类,看不到innerClass,体现了对接口编程的原则和依赖倒置原则。
public class Caller
{
public void callOut()
{
String para="me";
OutInterface out=new OuterClass().doit(para);
//如果有接口方法,即可 out.method();
}
}