参考程序:
public class Student {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void goHome(Traffic t){
System.out.println("学生:"+this.name);
t.run();
}
public Student(String name) {
this.name = name;
}
}
public abstract class Traffic {
protected double speed;
public void run(){
}
}
public class Bus extends Traffic{
@Override
public void run() {
System.out.println("时速为"+super.speed+"公里每小时的汽车正在嘀嗒嘀嗒的开着.");
}
public Bus(double busSpeed) {
super.speed = busSpeed;
}
}
public class Train extends Traffic {
@Override
public void run() {
System.out.println("时速为"+super.speed+"公里每小时的火车正在况且况且的开着.");
}
public Train(double trainSpeed) {
super.speed = trainSpeed;
}
}
public class AirPlan extends Traffic {
@Override
public void run() {
System.out.println("时速为"+super.speed+"公里每小时的飞机正在吴屋吴屋的开着.");
}
public AirPlan(double airPlanSpeed) {
super.speed = airPlanSpeed;
}
}
public class Test {
public static void main(String[] args) {
Traffic traffic1 = new Bus(40);
Student student = new Student("小明");
student.goHome(traffic1);
Traffic traffic2 = new Train(120);
Student student2 = new Student("小花");
student2.goHome(traffic2);
Traffic traffic3 = new AirPlan(300);
Student student3 = new Student("小红");
student3.goHome(traffic3);
}
}