Interface的精髓——《Thinking in Java》随笔025
1 //: InterfacePower.java 2 package cn.skyfffire; 3 4 import java.util.Vector; 5 6 /** 7 * 深究抽象类的应用 8 * 9 * user: skyfffire 10 * time: 下午3:20:35 11 */ 12 public class InterfacePower { 13 /** 14 * 为对象定义相同的接口 15 * 16 * @author skyfffire 17 * 18 */ 19 interface Student { 20 public String writeHomework(); 21 } 22 23 /** 24 * 抽象类的测试 25 * 26 * @param args 27 */ 28 public static void main(String[] args) { 29 // 定义一个班级属性用来封装该班级的学生 30 Vector<Student> classes = new Vector<Student>(); 31 32 // 定义三个学生,给予不同的写作业速度 33 Student xiaoMing = new Student() { 34 @Override 35 public String writeHomework() { 36 return "The xiaoMing is very slow to write homework."; 37 } 38 }; 39 40 Student xiaoHong = new Student() { 41 @Override 42 public String writeHomework() { 43 return "The xiaoHong is very quick to write homework."; 44 } 45 }; 46 47 Student xiaoGang = new Student() { 48 @Override 49 public String writeHomework() { 50 return "The xiaoGang is normal to write homework."; 51 } 52 }; 53 54 // 将三个同学添加到这个班级 55 classes.add(xiaoMing); 56 classes.add(xiaoHong); 57 classes.add(xiaoGang); 58 59 // 遍历这个班级的所有人,就算各自的习惯(方法实现)不同 60 // 但是都实现了同一个接口的同一个方法,所以可以拥有同样的行为。 61 for (Student s : classes) { 62 System.out.println(s.writeHomework()); 63 } 64 } 65 } 66 67 ///:~