I’m working on a project where I am trying to use generics but I’m having a hard time.
Say I have a many cars, all of them implemented in a different class (eg. audi.java, toyota.java, etc..) and each of them have a method called startCar(). Now I want to create a class Cars that lets other classes use these cars. However the following will not work. How should I go about implementing it?
public class Cars {
private MyCar mycar;
private class MyCar <MySpecificBrandOfCar>{
private MySpeicifBrand mySpecifcCar;
public MyCar(){}
}
public Cars(){
myCar = new myCar<audi>;
}
..other methods..
}
I also tried creating an interface, but that gave errors too.
Thanks
EDIT, attempted nfechner’s suggestion
Thanks for all the responses!
Would the following work (NB:GenericCar is an interface that is implemented by all cars (eg. audi.java) and has functions such as startCar()
public class Car{
private GenericCar mycar;
public Car(){
mycar = new audi();
}
}
Generics can’t be used to instantiate a class unfortunately, not in Java. Perhaps you could be a bit more specific about your intention, but you might find it useful to have some base class Car and have each specific car extend it. If you define the startCar() method in the base class Car, every subtype of Car will also have this method through polymorphism.
and so on.