Transition objects on Java and transition objects on Java
Transformation object: The subclass creates an object and assigns this object reference to the object of the parent class.
Syntax format: Father f = new Son ();
Note:
- The transformation object is created by the subclass, but the transformation object will lose some attributes and methods of the subclass.
- The method called by the transformation object is the method that has been inherited and rewritten by the subclass. Instead of the new method, or the original method of the parent class.
- The transformation object can manipulate the original attributes and functions of the parent class, regardless of whether these methods are overwritten.
- The transformation object can be forcibly converted to a subclass object. The forcibly converted object has all attributes and functions of the subclass.
Sample Code:
Public class Shangz {// The parent class int a = 1; int B = 2; void cal () {// The method System of the parent class. out. println (a * B);} public static void main (String [] args) {Shangz s = new ShangzDemo (); s. cal (); // Method s of the subclass called by the transformation object. err (); // error reported, the transformation object has lost the subclass attribute} class ShangzDemo extends Shangz {// subclass inherits the parent class void cal () {// subclass override the parent class method System. out. println (a + B);} void err () {// subclass's own method System. out. println (a/B );}}
Transformation object: The object referenced by the parent class is converted to the subclass type (forced type conversion ).
Syntax format:
Father f = new Son ();
Son s = (Father) f;
Error Syntax: (compile does not report an error, run reports an error)
Father f = new Father ();
Son s = Son (f );
Note:
- To perform a downward transformation, you must first perform an upward transformation. Otherwise, exceptions may occur.
- Transformation objects can reference attributes and methods of child classes and parent classes.
Code example:
Public class Shangz {// The parent class int a = 1; int B = 2; void cal () {// The method System of the parent class. out. println (a * B);} public static void main (String [] args) {Shangz s = new ShangzDemo (); ShangzDemo d = (ShangzDemo) s; d. cal (); // call the method d of the parent class. div (); // The Shangz serr = new Shangz (); ShangzDemo derr = (ShangzDemo) serr; derr. cal (); // No compilation error, conversion exception occurred during running} class ShangzDemo extends Shangz {// subclass inherits the parent class void cal () {// subclass override the parent class method System. out. println (a + B);} void div () {// subclass's own method System. out. println (a/B );}}
Finally, object transformation is widely used in generics.