Generics: Polymorphism with generics

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

In An Introduction To Generics we learned about declaring and using generics. In this part of the tutorial we are going to learn polymorphism with generics.

Consider this declarations.

  • List is the base type.
  • String is the generic type
  • ArrayList is the base type.
  • String is the generic type.

There is a simple rule. The type of declaration must match the type of object you are creating.

You can make polymorphic references for the base type NOT for the generic type. Hence the first statement is valid while second is not.

For the sake of this tutorial and further tutorials, Consider classes Vehicle, Car and Bike

  • Bike extends Vehicle
  • Car extends Vehicle
  • Every class has service() method

Vehicle class

Bike Class

Car class

and we have a Mechanic class who can do the servicing of all the vehicles.

  •   mechanic.serviceVehicles(vehicles)  works fine because we are passing ArrayList<Vehicle>  to the method that takes List<Vehicle> .
  •   mechanic.serviceVehicles(bikes)  and  mechanic.serviceVehicles(cars)  does not compile because we are passing ArrayList<Bike>  and ArrayList<Car>  to a method that takes List<Vehicle> .

Now why does this happen? Isn’t it obvious that we use polymorphism and pass a subtype list to a method that takes supertype. Why doesn’t generics allow this?

Consider this method

and if you were allowed to pass a List<Bike>  to addVehicle(List<Vehicle> vehicles)  using  mechanic.addVehicle(bike)  this method would have added a Car to the list of Bike which is plain wrong. Hence generics does not allow passing a subtype of generic type. This is because at runtime, the Collections framework does not have this generic information. So even if you declare  List<Vehicle> vehicles = new ArrayList<Vehicle>();  , This type safety is only at compile time. At runtime, this becomes List vehicles = new ArrayList(); . That’s right, all the type safety is lost. This is called as Type Erasure. 

But there is a workaround for this… We need to use the wildcard operator to be able to pass a subtype generic type to super type collection. We are going to learn the wildcard operator in the next part of this tutorial.







Share Button

4 comments for “Generics: Polymorphism with generics

  1. October 26, 2013 at 4:31 am

    Absolutely indited content material , thanks for selective information .

  2. October 28, 2013 at 8:59 pm

    Hey very nice website!! Guy .. Excellent .. Amazing .. I will bookmark your website and take the feeds also

  3. sunil kumar
    June 28, 2015 at 4:09 pm

    very nice contents and nice site

Leave a Reply to sunil kumar Cancel reply

Your email address will not be published. Required fields are marked *