Android中定义接口的用法
1、接口方法用于回调(这里定义接口是为了使用其接口方法):01
public inte易做图ce ICallback {
02
public void func();
03
}
04
05
public class Caller {
06
ICallback callback;
07
public void doCallback() {
08
callback.func();
09
}
10
11
public void setCallback(ICallback callback) {
12
this.callback = callback;
13
}
14
15
}
16
17
public class MainClass {
18
public MainClass() {
19
}
20
21
public static void main(String[] args) {
22
Caller caller = new Caller();
23
caller.setCallback(new ICallback () {
24
public void func() {
25
System.out.println("dosth");
26
}
27
});
28
caller.doCallback();
29
}
30
}
2、向上转型
01
inte易做图ce People{
02
void peopleList();
03
}
04
class Student implements People{
05
public void peopleList(){
06
System.out.println("I’m a student.");
07
}
08
}
09
class Teacher implements People{
10
public void peopleList(){
11
System.out.println("I’m a teacher.");
12
}
13
}
14
public class Example{
15
public static void main(String args[]){
16
People a; //声明接口变量
17
a=new Student(); //实例化,接口变量中存放对象的引用
18
a.peopleList(); //接口回调
19
a=new Teacher(); //实例化,接口变量中存放对象的引用
20
a.peopleList(); //接口回调
21
}
22
}
23
运行结果:
24
I’m a student.
25
I’m a teacher.
3、常量接口(这里不在讲)
补充:移动开发 , Android ,