0

Is there any way to generate different types of objects from one method without using long and complicated if-statements?

Lets say I've created an abstract class called Vehicle. Vehicle has a constructor like this:

public abstract class Vehicle {
  int mileage;

  public Vehicle (int mileage) {
    this.mileage = mileage;
  }
}

Now, I've created lots and lots of different types of vehicles that all inherits Vehicle, such as DuneBuggy, SmallCar, MediumCar, BigCar, FastCar, OldCar, NewCar, PickUpTruck, SmallTruck, MediumTruck, LargeTruck, Bicycle, Tram, Train and so forth and so on. To my understanding they're now all Vehicles since they inherit Vehicle.

Is there any way I can get vehicle type from user together with mileage and create the correct type of vehicle by passing it to one method no matter what type of vehicle the user has selected? Something like this:

public void createNewVehicle (Variable someKindOfWayToPickVehicleType, int mileage) {
  // Create a new vehicle where exact class is decided by someKindOfWayToPickVehicleType variable
}
timmyBird
  • 223
  • 3
  • 7
  • 1
    See http://stackoverflow.com/questions/9174359/create-different-objects-depending-on-type – jarmod Nov 22 '15 at 21:55
  • Use an `enum` if you have a fixed number of vehicles. Each element in the `enum` could have a "create" method of it's own, which returned the correct type of vehicle – MadProgrammer Nov 22 '15 at 21:57
  • http://stackoverflow.com/a/29853592/180100 is an option –  Nov 22 '15 at 21:58

1 Answers1

0

This solved the problem for me:

public static Car createCar(Class model, int mileage) {
    try {
        Object o = Class.forName(model.getName())
                .getConstructor(int.class)
                .newInstance(mileage);
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return (Car)o;
}

If anyone has comments or feedback on this approach I'm always eager to learn.

timmyBird
  • 223
  • 3
  • 7