1 public class Student { 2 3 public static void main(String[] args) { 4 Faculty f= new Math(); 5 f.SetCourse(new BasisOfComputerEngineering()); 6 f.urriculum(); 7 } 8 } 9 10 //选课11 interface CurriculaVariable{12 //所有课程的抽象方法13 void urriculum();14 }15 //各门课程16 class BasisOfComputerEngineering implements CurriculaVariable{17 18 @Override19 public void urriculum() {20 System.out.println("选择了计算机基础");21 }22 }23 24 //系25 abstract class Faculty implements CurriculaVariable{26 //系中聚合选课27 protected CurriculaVariable cv;28 public void SetCourse(CurriculaVariable cv) {29 this.cv = cv;30 }31 }32 //数学系33 class Math extends Faculty{34 35 @Override36 public void urriculum() {37 System.out.println("数学系选课");38 ((CurriculaVariable) cv).urriculum();39 }40 41 }
输出为: