I have an Object called CAR declared as follows:
public class Car{
public int NumberOfWheels;
}
and using another class I can retrieve three of its subclasses.
As follows:
public TruckA getCarA(int param){
return new TruckA () {NumberOfWheels = param}
}
public TruckB getCarB(int param){
return new TruckB () {NumberOfWheels = param}
}
public TruckC getCarC(int param){
return new TruckC () {NumberOfWheels = param}
}
How do I write in using generics ?
(I know it is too simple, I need an example for a more complicated case)
I want to create a method that creates a new (T), enters the parameter and returns it.
something like
public TruckC getCarC(int param){
return getTruck<TruckC>(param)
}
Only that :
1. TruckA/B/C dont have constructor.
2. Car has no constructor. initialized using {}.
3. The method should receive only classes that derive from Car so that it can use its initialization ( {} ).
(something equivalent to ?? extends ? in java generics)
Possible ?
Thanks.
1 Answer