interface People {
void peopleList();
}
class Student implements People {
public void peopleList() {
System. out .println( "I’m a student." );
}
}
class Teacher implements People {
public void peopleList() {
System. out .println( "I’m a teacher." );
}
}
public class Example {
public static void main(String args[]) {
People a; // 聲明接口變量
a = new Student(); // 實例化,接口變量中存放對象的引用
a.peopleList(); // 接口回調
a = new Teacher(); // 實例化,接口變量中存放對象的引用
a.peopleList(); // 接口回調
}
}
二、向上轉型與接口回調的區別
向上轉型是對象之間轉型,與接口回調形式相似擔心本質不一樣。
從實現了某接口的對象,獲得對此接口的引用,與向上轉型爲這個對象的基類,實質上效果是同樣的。這些對象均可以調用基類型提供的方法,對於接口來講就是回調接口中的方法,對於父類來講就是調用父類的方法。固然在向上轉型的狀況下,還牽涉到子類重寫(
Override
)父類方法的情形。