I am trying to correctly understand how to use generics. I have been searching on it all morning but I get confused when the tutorials start adding multiple generic values, or using very abstract terms which I am still wrestling with.
I am still learning so any general advice is welcome, but I would like to specifically figure out the syntax for the method returning the generic class.
For example consider:
public class GenericsExample4 {
public static void main(String args[]) {
Car car;
Truck truck;
car = buy(Car.class, 95);
truck = buy(Truck.class, 45);
}
// HELP HERE!
public static <T extends Vehicle> T buy(Class<T> type, int topSpeed) {
// create a new dynamic class T . . . I am lost on syntax
return null; // return the new class T. I am lost on the syntax here :(
}
}
interface Vehicle {
public void floorIt();
}
class Car implements Vehicle {
int topSpeed;
public Car(int topSpeed) {
this.topSpeed = topSpeed;
}
@Override
public void floorIt() {
System.out.println("Vroom! I am going " + topSpeed + " miles per hour");
}
}
class Truck implements Vehicle {
int topSpeed;
public Truck(int topSpeed) {
this.topSpeed = topSpeed;
}
@Override
public void floorIt() {
System.out.println("I can only go " + topSpeed + " miles per hour");
}
}
Can someone point out how to tie together this generic method?
Aucun commentaire:
Enregistrer un commentaire