# <span class="fa-stack"><i class="fa-solid fa-circle fa-stack-2x"></i><i class="fa-solid fa-book fa-stack-1x fa-inverse"></i></span> Checked Casts - Recall lecture on safety ```java class A { int x; } class B extends A { float y; } class C extends A { char c; } void f (B b) { A a = b; // upcast always safe } void g (A a) { B b = (B) a; // downcast must be checked } f (new B()); // OK g (new C()); // ClassCastException ``` :fa fa-question-circle: What makes upcasting safe? What makes downcasting unsafe? ---
* Ok, because `List[B] <: List[A]` * `List` is _covariant_ * If `B<:A` then `List[B]<:List[A]` * Generally, type constructor `T[-]` is _covariant_ if `B<:A` implies `T[B]<:T[A]`
- Outside the scope of this course - Bounded polymorphism (Java, C#, Scala, Flow) - Java's use-site variance and wildcards - Adhoc polymorphism, typeclasses, implicit params - Check out Scala and Typescript