Casting Objects Flashcards

1
Q

Give an example of a casting that doesn’t work and describe how to make it work !

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Give the rules to keep in mind when casting variables !

A

Here are some basic rules to keep in mind when casting variables:

  1. Casting an reference variable from a subclass to a superclass doesn’t require an explicit cast.
  2. Casting an reference variable from a superclass to a subclass requires an explicit cast.
  3. The compiler will not allow casts to unrelated types.
  4. 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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Give a clear example that violates the last rule !

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is a ClassCastException ?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly