mercredi 30 mars 2016

Returning an interface object from a method without instantiating an (unknown) concrete type

I'm sure there's some solution or pattern to this but i'm having trouble articulating the question to find the right answer.

I have an interface, ICar:

public interface ICar {
void SetMake(String make);
String GetMake();
}

I have a class, Car:

public class Car implements ICar {
private String make;

public void SetMake(String make) { this.make = make; }

public String GetMake() { return make; }

And I have a method in another class, which does not know about Car. In the spirit of polymorphism I'd like this method to return an ICar, so that someone could create their own implementation of ICar and utilize the method for their car:

...//class preamble
public ICar myMethod() {
    ICar myCar = new ICar();
    myCar.SetMake("Ferrari");
    return myCar;
}

I'm not sure why something like this can't work. As ICar contains the method SetMake, every implementation must also contain this method. Surely the jvm could in some way queue up the method calls and then run them when a concretion of the methods is available?

Another idea would be to pass a newly created implementation of ICar as a parameter to myMethod and call its methods, but I feel like this may not be such a clean implementation, as I would need to create an instance of Car each time. Also if there is no parameter-less constructor, i would have to instantiate it with dummy data (also not clean).

I feel like i'm lacking some understanding to see how to implement something like this, and was wondering if anyone might be able to help?

Thanks.

Aucun commentaire:

Enregistrer un commentaire