To determine which statements will compile, let's analyze each option:
A. Beagle b2 = (Beagle) dog1;
This statement will not compile because it is trying to cast a Dog
object (dog1
) to a Beagle
object. However, dog1
is not an instance of Beagle
, so the cast is not valid.
B. Runtime Exception
This option is not applicable as it is not a valid code statement.
C. Beagle b4 = dog2;
This statement will not compile because it is trying to assign a Dog
object (dog2
) to a Beagle
variable (b4
). In Java, you cannot assign an object of a superclass to a variable of its subclass type without explicit casting.
D. None of the above statements will compile
This option is incorrect because statement A will compile.
Therefore, the correct answer is A) Beagle b2 = (Beagle) dog1.