This is a very simple example of Java Generics. My issue here is why doesn't the compiler show compile error in intellij 13 with Java 7 without running the code, when the class is expecting a type that implements Vehicle and not a type that implements AirUnit when adding my list of AirUnits in an arraylist that expect a Vehicle in the HighWay Class.
Vehicle:
public interface Vehicle {
void goForward();
}
AirUnit:
public interface AirUnit {
void fly();
}
The Highway class that takes an array of vehicles and run them and prints their toString().
import java.util.ArrayList;
public class HighWay<T extends Vehicle> {
private ArrayList<T> vehicles;
public HighWay(ArrayList<T> vehiclesOnTheRoad){
this.vehicles = vehiclesOnTheRoad;
}
public void moveTheVehicles(){
for(T vehicle: vehicles){
System.out.println(vehicle);
}
}
}
The Client
import java.util.ArrayList;
public class Client {
public static void main(String[] args) {
Vehicle car = new Car();
Vehicle bike = new Bike();
AirUnit plane = new Plane();
ArrayList<Vehicle> vehicles = new ArrayList();
ArrayList<AirUnit> airUnites = new ArrayList();
airUnites.add(plane);
vehicles.add(car);
vehicles.add(bike);
// should show compile error because HighWay is expecting something
// that implements Vehicle but it is now showing any errors
// until I run the app and it breaks in the loop.
HighWay<Vehicle> highWay = new HighWay(airUnites);
highWay.moveTheVehicles();
}
}