內部類面試題(一)
阿新 • • 發佈:2018-12-26
按照要求,補齊程式碼
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中就是一個匿名內部類。