During the runtime of my programme, I would like to identify the type of an Object I would need to instantiate.
As an example: If a user is travelling from A to B, he can choose a transport method: car or push bike, Both will enable the user to travel, but the actual work processes are different. In a car you need to shift gears to move, on a bike you need to paddle. They would have a common set of methods, ie: "move", but their implementation would be different.
The rest of the programme doesn't need to know how 'move' is implemented...
Imagine:
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();
}
}
How can I now use the Bike or Car methods when I pass transportMethod back to another Class?
Thanks!
Chris
They would have a common set of methods, ie: "move", but their implementation would be different.
That sounds like they should both implement the same interface or extend the same abstract superclass then. Use that interface or superclass instead of Object
in your Transport
class. Actually, it sounds like your Transport
class is more of a factory than transport in itself. But leaving that aside:
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;
}
}
See more on this question at Stackoverflow