Forcing a type conversion in Java is divided into the basic data type and the reference data type, where we discuss the latter, which is the coercion type conversion of the reference data type.
In Java, because of inheritance and upward transformation, subclasses can be converted very naturally to a parent class, but the parent class is converted to a subclass that requires casting. Because subclasses have more properties than the parent class and are more powerful, the parent class is forced to convert to subclasses. So, is it a success if the parent class is converted to a subclass? In fact, the forced type conversion between them is conditional.
When we construct an object with a type of constructor, the type of the object is determined, and it is said that its nature will not change any more. In Java we can use the parent class type to refer to it through an inherited, upward-shifting relationship, which is possible when we use a weaker type to refer to a more powerful object. However, it is not always possible to force a weaker type into a functionally strong object.
Give an example to illustrate. For example, there are father, son two objects in the system. First we construct a son object and then reference it with a father type variable:
Father Father = new Son ();
Here the Son object instance is transformed upward to father, but notice that the Son object instance is in memory or son type, but its ability is temporarily weakened, what if we want to be strong? Restore its object type!
Son son = (son) father;
This statement is feasible, in fact, the Father reference is still the father type, but the ability to strengthen it, to strengthen it to the son reference, son object instance in son's variable reference, restore the real, you can use all functions.
It is not always successful to mention that the parent class is coerced into a subclass, so under what circumstances does it fail?
Forcing a type conversion produces an error when the true identity of the reference type is the type of the parent class itself. For example:
Father Father = new Father ();
Son son = (son) father;
This system will throwClassCastException异常信息。
所以编译器在编译时只会检查类型之间是否存在继承关系,有则通过;而在运行时就会检查它的真实类型,是则通过,否则抛出ClassCastException异常。
所以在继承中,子类可以自动转型为父类,但是父类强制转换为子类时只有当引用类型真正的身份为子类时才会强制转换成功,否则失败。
Original link: http://www.cnblogs.com/chenssy/p/3393160.html
[Turn]java Increase (11)-----Coercion Type conversion