Get started with java-6.5 and make an upward transition
In this section, we will discuss the upward transformation.
1. Example
package com.ray.testobject;public class Sub extends Father {public static void main(String[] args) {Sub sub = new Sub();Father.say(sub);}}class Father {public void doSomeThing() {System.out.println(doSomething);}public static void say(Father father) {father.doSomeThing();}}
In the above example, Father. say (sub) transmits the sub class of father, which we call upward transformation.
2. Explanation
The above figure shows the inheritance relationship between the two classes.
The essence of the inheritance relationship is the relationship between is-a. Therefore, sub is actually the first sub-class set in father. It is also a father type. sub has all the features of father, there are also public domains and methods. Therefore, even if sub is referenced during the call, since sub actually has an implicit father object, it is also referenced to the father object, that is, the doSomeThing method of the father object is called.
3. Why is upward transformation?
We can also see that we finally call the father object method, so the sub conversion type is up.
Note: Child classes are superclasses of parent classes. Child classes have more methods than superclasses. In the process of upward transformation, some methods will be lost.
4. Let's talk about aggregation and inheritance.
In fact, in the coding process, aggregation is used most of the time and inheritance is rarely used, because inheritance has certain risks, especially the inheritance of source code is not known. Therefore, is it important to determine whether an inheritance is required?
I have summarized a sentence, that is, does the new class need to be transformed upwards? If you do not need it, you must consider the inheritance issue.
Summary: This chapter briefly discusses several points of attention for upward transformation.