Java's upward and downward transformations and java's downward Transformations
At the beginning, I started to get started with java transformation. Although I still don't know why it should be transformed, I 'd like to write down the syntax first.
Upward Transformation:
First, you must have a parent class, a subclass,
Person p = new Person ();
P = new Student ();
OK. This is the upward transformation, which can be simplified to: Person p = new Student ();
1) p is a reference of Person, pointing to the object of Student, p is not an object;
2) p can only be calledMember variables and member functions in the parent class,The new methods and Variable p in the subclass cannot be used, while the execution subject is the subclass subject.
For example, class Person {
Void eat () {system. out. println ("eating ...")}
Void sleep () {system. out. println ("sleep ...")}
}
Class Student extends Person {
Void eat () {system. out. println ("I am a student ")}
Void read () {system. out. println ("I am reading ...")}
}
P can call the eat method and execute the function subject in Student. You can also call the sleep method. The sleep method is not in the subclass, so the function subject in the parent class is executed;
However, the read method cannot be called because the Person does not have the read method;
Downward Transformation:
Downward transformation is based on the upward Transformation
Student s = (Student) p;
Similarly, s is not an object, but a reference.
S can call all methods in the parent class and subclass, and execute the function subject in the subclass. If not, execute the function subject in the parent class.
Summary:
1. A parent class reference can point to a subclass object, but a subclass reference cannot point to a parent class object.
2. Assign the subclass object directly to the parent class and call it upcasting for upward transformation.
For example, Father father = new Son ();
3. Assign the parent class reference pointing to the subclass object to the sub-class reference called downcasting, which requires forced transformation.
For example, father is a parent class reference pointing to a subclass object. father is assigned to the subclass to reference son, that is, Son son = (Son) father;
The Son before father must be added for forced conversion.
4. upcasting will lose the method unique to the subclass. However, the subclass overriding parent class method is valid.
I don't know if there are any errors here. Even if there are any errors, I can't find them now. Learn more, just like this.