In my study book, there's this example:
import java.util.*;
public class RentalGeneric<T> {
private List<T> rentalPool;
private int maxNum;
public RentalGeneric(int maxNum, List<T> rentalPool) {
this.maxNum = maxNum;
this.rentalPool = rentalPool;
}
public T getRental() {
return rentalPool.get(0);
}
public void returnRental(T returnedThing) {
rentalPool.add(returnedThing);
}
}
I find it strange that it compiles, since there is no definition of Class<T>
. What is the story about this? It says in my book that T
is for the type parameter but how do I know when to use it?
You could use it to rent cars, bikes ... You could use it directly like this:
RentalGeneric<Car> carRental = new RentalGeneric<Car>(10, aList);
Then when you'll do getRental
it'll return you a Car
object.
And you'll be able to put back a Car
with returnRental(aCar);
Or you could create a CarRental
class extending RentalGeneric<Car>
.
Same thing goes for whatever object you would like to rent.
T is generic Type here. It will be initialized while creating Object of RentalGeneric
class.
RentalGeneric<Double> rgS =new RentalGeneric<Double>(10, new ArrayList<Double>());
RentalGeneric<Integer> rgS =new RentalGeneric<Integer>(10, new ArrayList<Integer>());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With