匿名類別
Prerequisites:
抽象類別的匿名子類別
建立抽象類別Human,與抽象方法speak()
1
2
3
abstract class Human {
abstract void speak();
}
建立一個簡單的類別TestHuman,類別中有一個test()方法。
參數是Human類別,用來測試多型,只要是Human的子類別,都可以作為參數傳入。
1
2
3
4
5
public class TestHuman {
void test(Human human) {
human.speak();
}
}
建立TestHuman物件,並使用test()方法
1
2
3
4
5
6
public class Test {
public static void main(String[] args) {
TestHuman testHuman = new TestHuman();
testHuman.test(要在這裡建立匿名類別);
}
}
匿名的方式建立子類別1
語法
new 抽象類別() {}
- 呼叫test(),參數為
new 抽象類別() {}
1
testHuman.test(new 抽象類別 () {});
- 在花括號{}中,覆寫speak()
1
2
3
4
5
6
testHuman.test(new Human() {
@Override
void speak() {
}
});
- 加上要覆寫的內容
1
2
3
4
5
6
7
testHuman.test(new Human() {
@Override
void speak() {
// 覆寫的內容
System.out.println("說中文");
}
});
說中文
匿名花括號{}
在上一段程式碼利用花括號{}建立沒有名字的繼承抽象類別的子類別,可以視為花括號{}中的內容是子類別的body。
{
子類別的body
}
匿名的方式建立子類別2
- 宣告japan變數為父類別Human
- new 父類別Human()
- 加上花括號{}
- 覆寫speak方法 此時japan就是Human的子類別
1
2
3
4
5
6
7
Human japan = new Human() {
@Override
void speak() {
System.out.println("說日文");
}
};
japan.speak();
說日文
匿名的方式建立子類別3
- new 父類別Human()
- 加上花括號{}
- 覆寫speak方法
1
2
3
4
5
6
new Human() {
@Override
void speak() {
System.out.println("說日文");
}
}.speak();
說日文
類別的匿名子類別
除了抽象類別建立的匿名類別,一般類別也可以透過匿名的方式建立子類別
建立一個Car類別,裡面有一個print()方法。
1
2
3
4
5
public class Car {
public void print() {
System.out.println("car");
}
}
建立「匿名」Car的子類別,注意!加上花括號{},表達的不是Car這個類別,而是繼承Car的子類別。
1
2
3
4
5
6
7
8
9
public static void main(String[] args) {
Car toyota = new Car() {
@Override
public void print() {
System.out.println("我是Toyota");
}
};
toyota.print();
}
我是Toyota
1
2
3
4
5
6
7
8
public static void main(String[] args) {
new Car() {
@Override
public void print() {
System.out.println("我是Toyota");
}
}.print();
}
我是Toyota
方法參數為匿名類別
建立一個測試參數為Car的類別,TestCar.java
1
2
3
4
5
public class TestCar {
public void test(Car car) {
car.print();
}
}
方法參數為「匿名」Car的子類別,注意!加上花括號{},表達的不是Car這個類別,而是繼承Car的子類別,即便{}花括號的內容是空的,這裡的意思是子類別,不是Car這個類別,Car變成父類別,這個沒有名字的子類別擁有父類別繼承來的print()方法。
1
2
3
4
5
public static void main(String[] args) {
TestCar testCar = new TestCar();
// 建立Car的子類別
testCar.test(new Car() {});
}
car
覆寫(重寫)繼承Car的子類別的print()方法
1
2
3
4
5
6
7
8
9
public static void main(String[] args) {
TestCar testCar = new TestCar();
testCar.test(new Car() {
@Override
public void print() {
System.out.println("我是Toyota");
}
});
}
我是Toyota
介面(Interface)的匿名類別
建立一個Fly介面
1
2
3
public interface Fly {
void fly();
}
介面匿名步驟:
- new 介面()
- 加上花括號{}
- 覆寫fly方法
透過new 介面() {} 的方式,建立介面的匿名類別
方式1:
1
2
3
4
5
6
new Fly() {
@Override
public void fly() {
System.out.println("蚊子飛");
}
}.fly();
蚊子飛
方式2:
1
2
3
4
5
6
7
8
9
public static void main(String[] args) {
Fly mosquito = new Fly() {
@Override
public void fly() {
System.out.println("蚊子飛");
}
};
mosquito.fly();
}
蚊子飛