JAVA匿名內部類以及面試題
阿新 • • 發佈:2018-11-08
匿名內部類,相當於簡化的內部類
前提條件:有一個類(具體類或者抽象類)或者介面。
格式: new 類名或者介面名() {重寫方法;}
這裡new出來的物件相當於類的子類物件或者介面的實現類物件。
實質:建立的是繼承了類或實現了介面的子類匿名物件。
/* 匿名內部類面試題: 按照要求,補齊程式碼 interface Inter { void show(); } class Outer { //補齊程式碼 } class OuterDemo { public static void main(String[] args) { Outer.method().show(); } } 要求在控制檯輸出”HelloWorld” */ interface Inter { void show(); //public abstract } class Outer { //補齊程式碼 public static Inter method() { //子類物件 -- 子類匿名物件 return new Inter() { public void show() { System.out.println("HelloWorld"); } }; } } class OuterDemo { public static void main(String[] args) { Outer.method().show(); } }
分析:1、通過main方法中直接呼叫Outer.method().show()可以分析出method是一個靜態方法
2、Outer.method().show()是一個鏈式程式設計,Outer.method()是一個物件,即method()返回值為引用型別。
3、通過後面呼叫show()方法可以分析出method()引用的是一個Inter介面型別。