具体代码
//Travel.java
package org.example.test021;
public interface Travel {
public void travel();
}
//Person.java
package org.example.test021;
public class Person {
public Travel getTravel() {
return travel;
}
public void setTravel(Travel travel) {
this.travel = travel;
}
private Travel travel;
public void travel() {
travel.travel();
}
}
//AirplaneTravel.java
package org.example.test021;
public class AirplaneTravel implements Travel {
@Override
public void travel() {
System.out.println("乘坐飞机旅游!");
}
}
//TrainTravel.java
package org.example.test021;
public class TrainTravel implements Travel {
@Override
public void travel() {
System.out.println("乘坐火车旅游!");
}
}
//BicycleTravel.java
package org.example.test021;
public class BicycleTravel implements Travel {
@Override
public void travel() {
System.out.println("乘坐自行车旅游!");
}
}
//Main.java
package org.example.test021;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Person person = new Person();
Scanner sc = new Scanner(System.in);
System.out.println("请选择你想要的旅游出行方式:1、飞机;2、火车;3、自行车");
int i = sc.nextInt();
if (i == 1) {
person.setTravel(new AirplaneTravel());
}
else if (i == 2) {
person.setTravel(new TrainTravel());
}
else if (i == 3) {
person.setTravel(new BicycleTravel());
}
else {
System.out.println("不存在这种出行方式呦~");
}
person.travel();
}
}