The execution result of the following code is as follows:
class Building{}public class Barn extends Building{ public static void main(String[] args){ Building build1 = new Building(); Barn barn1 = new Barn(); Barn barn2 = (Barn)build1; Object obj1 = (Object)build1; String str1 = (String)build1; Building build2 = (Building)barn1; }}
The point of the question test is the forced conversion of the reference type. Note the following when converting the forced type of the reference type:
1. Conversion of reference types can only be performed between two classes with inheritance relationships. If the two classes do not have an inheritance relationship, the "non-convertible" error will be reported during compilation.
2. If the subclass object is forcibly converted to the parent class type, the compiled type of the converted child type object is converted to the parent class, but its runtime type is still child.
3. If you want to convert a variable of the parent type to a child type, this object is generally required to be a child type instance (the parent type is the compilation type, and the runtime type is the child type ). Otherwise, a classcastexception exception is reported during the execution even though it can be passed during compilation.
4. In case 3, use the instanceof operator to determine before forced type conversion. The first operand of the instanceof operation is usually a reference type variable, and the second operand is generally a class or interface, such as "barn1 instanceof Barn ". Instanceof is used to determine whether the previous object is an instance of the following class (or its subclass or implementation class.
5. note that when using the instanceof operator, the compiling type of the operand before the instanceof operator is either the same as that of the subsequent class or has an inheritance relationship, otherwise, the "non-convertible type" error will be reported during compilation.
According to the first point, we can see that the above question will report an error during compilation. The problem lies in the line "string str1 = (string) build1.
Scjp test preparation-10