Casting Objects Flashcards
Give an example of a casting that doesn’t work and describe how to make it work !
When we try to assign a reference variable of a superclass type directly to a reference variable of a subclass type in Java, it will result in a compilation error
Give the rules to keep in mind when casting variables !
Here are some basic rules to keep in mind when casting variables:
- Casting an reference variable from a subclass to a superclass doesn’t require an explicit cast.
- Casting an reference variable from a superclass to a subclass requires an explicit cast.
- The compiler will not allow casts to unrelated types.
- Even when the code compiles without issue, an exception may be thrown at runtime if the object being cast is not actually an instance of that class.
Give a clear example that violates the last rule !
public class Rodent {
}
public class Capybara extends Rodent {
public static void main(String[] args) {
Rodent rodent = new Rodent();
Capybara capybara = (Capybara)rodent; // Throws ClassCastException at runtime
}
}
This code creates an instance of Rodent and then tries to cast it to a subclass of
Rodent, Capybara.
Although this code will compile without issue, it will throw a ClassCastException at runtime since the object being referenced is not an instance of the Capybara class.
The thing to keep in mind in this example is the object that was created is not related to the Capybara class in any way.
What is a ClassCastException ?
An exception thrown at runtime in Java when there is an invalid cast operation, typically during downcasting, where the object’s actual type is not compatible with the target type of the reference variable