內部類的小練習
如下:
interface Inter{
public abstract void method();
}
class Test {
//補足代碼,通過匿名內部類
}
class InnerClassDemo2 {
public static void main(String[] args){
Test.function().method(); //分析此語句的實現功能。
}
}
補足以上代碼,要求使用到匿名內部類。
分析語句
Test.function().method(); //因爲直接通過Test類名調用,所以Test類中有靜態方法function(),function()這個方法運算後結果是一個對象,而且是一個Inter類型對象,因爲只有是Inter類型的對象,纔可以調用method()方法
補足後的完整代碼是:
interface Inter{
public abstract void method();
}
class Test {
//補足代碼,通過匿名內部類
static Inter function(){ //返回值是Inter類型的對象,當然可以是Inter類型的子類對象,這裏出現了多態
return new Inter(){ //實際上new的並不是Inter類型的對象,而是Inter的子類的對象。該子類實現了Inter接口
public void method(){
System.out.println("method run");
}
};
}
}
class InnerClassDemo2 {
public static void main(String[] args){
Test.function().method();
}
}
其中:
return new Inter(){
public void method(){
System.out.println("method run");
}
};
這個return 語句中含有一個匿名內部類,此匿名內部類首先實現了Inter 接口,後創建了一個此匿名內部類對象;
所以此匿名內部類是Inter接口的子類,return 語句返回的是Inter 接口的子類對象。
結果如下: