1. 定义接口
package com.guoyasoft;
public interface IStudy {
public boolean doHomeWork(String renwu);
public int learn(String course);
}
2. 写检查代码
package com.guoyasoft;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class TestIStudy {
public static void main(String[] args) {
try {
// 第1步:分派任务
Map<String,String> task = new HashMap<String,String>();
task.put("wuhao", "com.guoyasoft.StudentWH");
task.put("chenyuan", "com.guoyasoft.StudentCH");
String wuhaoClass = (String) task.get("wuhao");
//手动将需要的class类加载到虚拟机内存,返回class对象(类型对象)
Class classWuhao = Class.forName(wuhaoClass);
//newInstance()调用类的无参构造器,生成一个实例对象,等价于new 对象名()
IStudy wuhao = (IStudy) classWuhao.newInstance();
boolean isDone = wuhao.doHomeWork("抄10遍");
int score = wuhao.learn("法语");
System.out.println("isDone homework=" + isDone + "; 法语成绩:" + score);
String chenyuanClass = (String) task.get("chenyuan");
Class classChenyuan = Class.forName(wuhaoClass);
IStudy chenyuan = (IStudy) classWuhao.newInstance();
isDone = wuhao.doHomeWork("抄10遍");
score = wuhao.learn("法语");
System.out.println("isDone homework=" + isDone + "; 法语成绩:" + score);
} catch (Exception e) {
e.printStackTrace();
}
}
}
3. 任务提交前测试
执行TestIStudy
java.lang.ClassNotFoundException: com.guoyasoft.StudentWH1
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:190)
at com.guoyasoft.TestIStudy.main(TestIStudy.java:17)
4. 实现接口
提交作业1
package com.guoyasoft;
public class StudentWH implements IStudy{
@Override
public boolean doHomeWork(String renwu) {
System.out.println("开始做作业");
System.out.println("开始看手机");
System.out.println("开始玩游戏");
System.out.println("不做了");
return false;
}
@Override
public int learn(String course) {
System.out.println("不想学");
return 0;
}
}
提交作业2
package com.guoyasoft;
public class StudentCH implements IStudy {
@Override
public boolean doHomeWork(String renwu) {
System.out.println("游戏");
System.out.println("代做");
return true;
}
@Override
public int learn(String course) {
System.out.println("我喜欢");
return 90;
}
}
5. 提交代码后测试
运行TestIStudy类
开始做作业
开始看手机
开始玩游戏
不做了
不想学
isDone homework=false; 法语成绩:0
游戏
代做
我喜欢
isDone homework=true; 法语成绩:90
6. 面向接口编程的思想
使用接口,将各种各样类型的类抽象成同一种更高层级的类型,然后当作同一种类型进行批量处理