按照要求,补齐代码
interface Inter { void show(); }
class Outer { //补齐代码 }
class OuterDemo {
public static void main(String[] args) {
Outer.method().show();
}
}
要求在控制台输出”HelloWorld”
答案
interface Inter { void show(); }
class Outer {
//补齐代码
public static Inter method(){
return new Inter(){
void show(){
System.out.println("HelloWorld");
}
};
}
}
class OuterDemo {
public static void main(String[] args) {
Outer.method().show();
}
}
解析:这个题目挺有趣的,考了很多东西,一开始只能说我自己度懵逼了,是一个局部匿名内部类。 通过看主方法中的调用,Outer.method(),能直接用类名调用方法,
那么肯定该方法就是一个static方法,然后又直接调用了show()方法,说明这个method方法有一个返回值,其返回值类型就是实现该接口类的类型,因为只有接口中有show()这个方法。所以在method中就是一个匿名内部类。