Video in progress
How does converting an object to a parent type and back to a child type (upcast/downcast) work?
Assigning a child object to a parent-type variable is automatic and safe. The reverse needs an explicit cast like (Dog) animal, and if the object is actually a different type, a ClassCastException is thrown at runtime.
📖 Answer
The object itself never changes; only the "glasses" you look at it through change.
Animal a = new Dog(); // we see the Dog as an Animal
a.eat(); // only Animal methods are visible
Dog d = (Dog) a; // back to Dog: fine, the object is that type
Animal c = new Cat();
Dog wrong = (Dog) c; // ClassCastException: a Cat is not a Dog
To check before a cast, there has been a convenient syntax since Java 16:
if (a instanceof Dog dog) {
dog.bark(); // the dog variable exists only inside this block
}
The compiler itself stops a cast between completely unrelated types: (String) Integer.valueOf(1) doesn't compile.
On design: if you cast downward often in your code, the method you need probably isn't in the parent type. Casts are natural inside equals(Object o) or where a library hands you an Object, but if they pile up in business logic, rethink the hierarchy.
Sign up to mark studied questions and save your progress.