List is an interface; ArrayList and LinkedList are classes that implement it. Use the general type for variables, parameters and return types, and name the class only after new: List<String> names = new ArrayList<>();. Later lines can use only what List promises, so switching to LinkedList changes only that line and its import.
Moving up to a general type is an upcast. It is automatic and always safe, because a Square is a Shape. Moving down is a downcast. It needs a written cast and is checked at run time: if the object is not of the cast type, Java throws a ClassCastException. In Java 17, s instanceof Square q tests the actual class and, when true, gives you q: the same object, typed as Square.
public class Casts {
public static void main(String[] args) {
Shape s = new Square(2); // upcast: automatic
// double x = s.side; // does not compile: Shape has no side
if (s instanceof Square q) { // true: actual class is Square
System.out.println(q.side); // 2.0
}
// Circle c = (Circle) s; // compiles, then ClassCastException
}
}
CAST RULE
downcast to T succeeds⟺actual class is T or a subtype of T
For a non-null reference and a cast the compiler accepts (it refuses one between two classes when neither extends the other). T is the target class or interface. A subtype: the class extends T or, for an interface T, it or a superclass implements T or an interface extending T.