1、接口方法用于回调 (这里定义接口是为了使用其接口方法):

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();

}

}

2、向上转型

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.

3、常量接口(这里不在讲)

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐