有了前阶段匿名内部类的基础后,今天我们看一道匿名内部类的经典面试题。
请看代码:
我们先定义一个接口InterTest和它的show方法:
interface InterTest{
public abstract void show();
}
然后我们定义一个OuterAnonyTest类,代码省略:
class OuterAnonyTest{
//略
}
在main中有这样一行代码:
OuterAnonyTest.method().show();
要求补齐OuterAnonyTest代码,输出Hello World。
接下来我们一步步分析OuterAnonyTest.method().show();:
看到OuterAnonyTest.method(),
类名直接调方法,说明OuterAnonyTest里有一个静态方法method。
看到OuterAnonyTest.method().show() ,
链式编程,说明method返回对象所以才能继续调方法,
又因为接口里有show方法,所以准确的说,method返回了接口。
public static InterTest method(){
return new InterTest() {
@Override
public void show() {
// TODO Auto-generated method stub
}
};
}
输出Hello World。
在show方法里输出即可:
@Override
public void show() {
// TODO Auto-generated method stub
System.out.println("Hello World.");
}
因此补齐 OuterAnonyTest代码,最后结果如下:
class OuterAnonyTest{
//补齐代码 输出Hello World.
public static InterTest method(){
return new InterTest() {
@Override
public void show() {
// TODO Auto-generated method stub
System.out.println("Hello World.");
}
};
}
}
抽丝剥茧,一步步分析,得出答案。