一、接口方法用於回調 (這裏定義接口是爲了使用其接口方法):java
public interface ICallback { public void func(); } public class Caller { ICallback callback; public void doCallback() { callback.func(); } public void setCallback(ICallback callback) { this.callback = callback; } } public class MainClass { public MainClass() { } public static void main(String[] args) { Caller caller = new Caller(); caller.setCallback(new ICallback () { public void func() { System.out.println("dosth"); } }); caller.doCallback(); } }
二、向上轉型this
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(); //接口回調 } } 運行結果: I’m a student. I’m a teacher.三、常量接口(這裏不在講)