更改Java对象类型?

den*_*r81 0 java

在我的程序运行期间,我想确定我需要实例化的对象的类型.

例如:如果用户从A到B旅行,他可以选择一种运输方式:汽车或自行车,两者都可以让用户旅行,但实际的工作流程是不同的.在汽车中,你需要换档才能在自行车上移动,你需要划桨.他们会有一套共同的方法,即:"移动",但它们的实现会有所不同.

该计划的其余部分不需要知道如何实施"移动"......

想像:

public class Transport {
   public Object transportMethod;

   public Transport(tMet) {
      if (tMet.equals("car")) {
         transportMethod = new Car();
      }
      else if (tMet.equals("bike")) {
         transportMethod = new Bike();
      }
   }

   public Object returnTransportMethod() {
      return transportMethod();
   }
}
Run Code Online (Sandbox Code Playgroud)

当我将transportMethod传递回另一个类时,我现在如何使用Bike或Car方法?

谢谢!

克里斯

Jon*_*eet 9

他们会有一套共同的方法,即:"移动",但它们的实现会有所不同.

听起来他们应该实现相同的接口或扩展相同的抽象超类.使用该接口或超类而不是Object您的Transport类.实际上,听起来你的Transport班级本身更像是一个工厂而不是交通工具.但是把它放在一边:

public interface Vehicle {
    void move();
}

public class Bike implements Vehicle {
    public void move() {
        // Implementation
    }
}

public class Car implements Vehicle {
    public void move() {
        // Implementation
    }
}

public class VehicleFactory {
   public Vehicle vehicle;

   public VehicleFactory(String method) {
      if (method.equals("car")) {
         vehicle = new Car();
      } else if (method.equals("bike")) {
         vehicle = new Bike();
      }
      // TODO: Decide what you want to do otherwise...
   }

   public Vehicle getVehicle() {
      return vehicle;
   }
}
Run Code Online (Sandbox Code Playgroud)