Bottom Restricted Template

I tried to understand the concept and rationale of the lower restricted template in Java Generics. I can understand the reasoning behind the upper bounded wildcard for read-only and where and how to use it. I am still not able to understand the bottom restricted template. I have a set of classes that follow below the hierarchy. ( Automobile- base class.)

Automobile
    - Bus
        - Minibus
        - Doubledecker
        - Electricbus
    - Car
        - Sedan
        - Hatchback
        - Coupe
    - Truck
        - Minivan
        - Pickuptruck
        - Suv
            - Fullsuv
            - Midsuv

Now I'm trying to create a (flexible) list and add objects of different types to it.

import java.util.ArrayList;
import java.util.List;

public class Garage {

    public static void main(String[] args)
    {
        List<? super Suv> list = null;

        Suv s = new Suv();
        Truck t = new Truck();
        Automobile a = new Automobile();

        list = new ArrayList<Suv>();
        list.add(s); // declared as List<? super Suv> but actually List<Suv>. No compilation error

        list = new ArrayList<Truck>();
        list.add(t); // declared as List<? super Suv> but actually List<Truck>. Compilation error

        list = new ArrayList<Automobile>();
        list.add(a); // declared as List<? super Suv> but actually List<Automobile>. Compilation error
    }
}

Suv List<? super Suv>. , Truck Automobile . List<? super Suv> , Suv ? Truck Automobile . ?

+4
1

List<? super Suv> ", - Suv".

:

list = new ArrayList<Automobile>();
list.add(a); // where a is an Automobile

, ArrayList<Automobile> ", - Suv".

: Automobile , - Suv.

,

  • list List<Truck> ( Truck - Suv)
  • t a Car ( a Car Automobile)

, Car Trucks.


:

+3

All Articles