1.1. 匿名內部類
1.1.1. 書寫格式
class A{}:表示定義一個A類
new A():表示創建A類的一個對象
new A(){}:表示創建A類的一個匿名子類的對象,後面大括號中的內容,就是匿名子類中的內容;
interface Inter{}:表示創建了一個接口Inter
new Inter(){}:表示創建了接口Inter的一個匿名實現類的對象,後面大括號中的內容,就是匿名實現類中的內容;
1.1.2. 演示代碼
1.1.3. 使用場景
當要使用一個類的子類(或接口的實現類)時,如果這個子類只會使用一次,就沒必要專門定義一個類出來,可以使用匿名內部類的方式調用;
問題:補足下面的代碼:
interface Inter{
public void test();
}
class Demo2 {
public static void useInter(Inter inter){
inter.test();
}
public static
void main(String[] args) {//調用useInter函數,在控制檯輸出 "Hello,World!"
}
}
原來的做法:
//問題:補足下面的代碼:
interface Inter{
public void test();
}
class InterImpl implements Inter{
public void test() {
System.out.println("Hello,World!");
}
}
public
class NoNameDemo2 {public static void useInter(Inter inter){
inter.test();
}
public static void main(String[] args) {
//調用useInter函數,在控制檯輸出 "Hello,World!"
useInter(new InterImpl());
}
}
問題:我們為了解決上面的需求,手動創建了Inter接口的一個實現類。這個實現類僅僅只是在這裡使用一次,專門創建一個類,有點麻煩。
新的做法:使用匿名內部類:
閱讀更多 IT極客學社 的文章