In Java, it is possible that the parent class is forcibly converted to a subclass.
Previously, the apprentice asked a question: in Java, can a parent class object be converted to a corresponding subclass object?
If it is possible, let's talk about this problem today. Let's look at the following code:
Package cn.com. hanbinit. test;/*** check whether the parent class can be strongly converted to a subclass * @ author icer **/public class ConvertPro extends Father {public static void main (String [] args) {Father father = new Father (); Father father1 = new ConvertPro (); ConvertPro son = new ConvertPro (); // ConvertPro son1 = (ConvertPro) new Father (); // son = (ConvertPro) father; son = (ConvertPro) father1 ;}/ *** parent class ** @ author icer **/class Father {private String name; public String getName () {return name;} public void setName (String name) {this. name = name ;}}
The two lines commented out by the code above will run incorrectly. according to the Code, only when the parent class object itself is new from the subclass can it be forcibly converted into a subclass object in the future.
The subclass inherits all the attributes and methods of the parent class. That is to say, the content of the subclass should be larger than that of the parent class. if a parent class is converted into a subclass in a normal environment, precision will be lost. however, if the parent class object itself uses
Subclass is new,It is similar to a person who is a son role. After installing a father for a while, the role can be converted back in the future. However, a father can never pretend to be a son..