close
介面的多型可以把他想成是一個統一的行為管理介面
在implements相同interface的class,
就可以用interface來當作其宣告名稱
進而利用該宣告來處理其相同的動作
要達成多形的條件就是class必須實體化並且有implements該interface
舉例來說
T1, T2皆implements相同的介面Iface
public interface Iface {
void show();
}
而我們想用一個方法來使用不同class的show方法
就可以宣告一個方法參數是interface來控制
public class Test {
public static void main(String[] args){
Iface t1 = new T1();
Iface t2 = new T2();
toShow(t1);
toShow(t2);
}
static void toShow(Iface iface){
iface.show();
}
}
1. 官網https://docs.oracle.com/javase/tutorial/java/IandI/interfaceAsType.html
2. 參考網頁https://stackoverflow.com/questions/7275844/interface-as-a-type-in-java
文章標籤
全站熱搜