As with primitives, objects can be cast both explicitly and implicitly.
Implicit casting happens when the source type extends or implements the target type (casting to a superclass or interface).
Explicit casting has to be done when the source type is extended or implemented by the target type (casting to a subtype). This can produce a runtime exception (ClassCastException
) when the object being cast is not of the target type (or the target's subtype).
Float floatVar = new Float(42.0f);
Number n = floatVar; //Implicit (Float implements Number)
Float floatVar2 = (Float) n; //Explicit
Double doubleVar = (Double) n; //Throws exception (the object is not Double)