| The Java transformation problem is not complicated, just remember the word: The parent reference points to the subclass object.
What is a parent class reference to a subclass object, and listen to me slowly.
Start with 2 nouns: upward transformation (upcasting), downward transformation (downcasting).
For example: There are 2 classes, Father is the parent class, and the son class inherits from father.
Father f1 = new Son (); This is called upcasting (upward transformation)
Now the F1 reference points to a son object
son S1 = (son) F1; This is called downcasting (downward transformation)
Now F1 still point to son object
A 2nd example:
Father F2 = new Father ();
Son s2 = (son) F2; Error, subclass reference cannot point to parent class object
You might ask, in the 1th example: son s1 = (son) F1; ask what is right.
Very simple because F1 points to a subclass object, Father f1 = new Son (); The subclass S1 Reference can of course point to the child class object.
The F2 is passed to a Father object, Father f2 = new Father (); The subclass S1 reference cannot point to the parent class object.
Summarize:
1. The parent class reference points to the child class object, and the subclass reference cannot point to the parent class object.
2. The target class object is directly assigned to the parent class reference called upcasting, which transforms upward without casting.
such as: Father F1 = new Son ();
3. Assign the parent class reference to the subclass object to the subclass reference called down Transformation (downcasting), to cast.
For example, F1 is a parent class reference to a subclass object. Assign F1 to the subclass reference S1 that son S1 = (son) F1;
Where the F1 front (Son) must be added, cast.
|