class CovariantException extends RuntimeException { } class Food { public String toString() { return "some generic food, maybe tofu"; } } class Steak extends Food { public String toString() { return "a juicy steak"; } } class Grass extends Food { public String toString() { return "some grass and clover"; } } class Animal { void eats(Food v) throws CovariantException { System.out.println("An animal eating " + v); } } class Lion extends Animal { void eats(Steak v) throws CovariantException { System.out.println("A lion eating " + v); } @Override final void eats(Food v) throws CovariantException { if (!(v instanceof Steak)) throw new CovariantException(); eats((Steak) v); } } public class FoodChain { public static void main(String[] args) { new Animal().eats(new Food()); new Lion().eats(new Steak()); new Lion().eats((Food) new Steak()); new Lion().eats(new Food()); // don't fool the lion -> CovariantException } } else echo ../Stp/exercises/Java/40-encoding_variance.correc import java.util.ArrayList; import java.util.List; import java.util.Arrays; class Covariance { public static void main(String[] args) { List x = new ArrayList<>(Arrays.asList(1)); // x.add(1.0); // Impossible (incompatible types) // x.add((Number) 1.0); // Impossible (incompatible types) Number n1 = x.get(0); // Possible // Integer n2 = x.get(0); // Impossible (incompatible types) List y = new ArrayList<>(Arrays.asList(1)); y.add(Integer.valueOf(2)); // Possible // Number m1 = y.get(0); // Impossible (incompatible types) // Integer m2 = y.get(0); // Impossible (incompatible types) Object m2 = y.get(0); // Possible } }