今天也不准备记录太多的东西,就想把一个关于匿名内部类的一个面试题分享一下。
匿名内部类题目内容
按照要求,补齐代码
interface Inter {
void show();
}
class Outer {
//补齐代码
}
class OuterDemo {
public static void main(String[] args) {
Outer.method().show();
}
}
上面就是这道小小的面试题,如果今天没有上课,我估计完成不了,首先分析main方法中的方法调用语句,Outer.method(),Outer是直接在后面加了个点调用的method()方法,说明method()方法是Outer类中的一个静态方法,所以我们可以先在代码上写下这个method方法。
然后我们继续看后面,调用的接口Inter的show()方法,说明前面的Outer.method()的类型是Inter类型的,也就是接口类型的,要不然也调用不了这个show()方法,所以我们可以确定method()方法应该有一个Inter类型的返回值。
所以我们应该在method方法里面写一个匿名内部类并将它作为method方法的返回值,最后代码如下。
代码解答
interface Inter{
void show();
}
class Outer{
public static Inter method(){
return new Inter(){
public void show(){
System.out.println(“Hello World”);
};
};
}
}
class OuterDemo{
public static void main(String[] args){
Outer.method().show();
}
» 订阅本站:https://www.kgraph.cn
» 转载请注明来源:九五青年博客 » 《Java关于匿名内部类的一个面试题》