/* on transition and down transformation (object polymorphism)
* On transition: is a subclass object referenced by the parent class, format: Parent p=new son
* That is to say, the prerequisite for a transition must be two classes with an inheritance relationship.
* When invoking a method, the upper transformation object can only invoke methods in the parent class, and if the method of calling the subclass will error
* Down Transformation: is the parent class is cast down to the child class object
* If the parent class object must be an object that has been transformed.
*
* Code Example: */
1 Abstract classparent{2 Abstract voidgrow ();3 }4 classSonextendsparent{5 voidgrow () {6System.out.println ("I grew up better than my father."));7 }8 voidDance () {9System.out.println ("I Can Play");Ten } One } A Public classTest { - Public Static voidMain (string[] args) { - //on the transformation, use the parent class to refer to the object of the child class theParent p=NewSon (); - //calling methods in the parent class - P.grow (); - //p.dance (); There will be an error because there is no dance () method in the parent class + - //Make a forced transition to an object that has been transformed +Son s=(Son) p; A //calling a method in a subclass at s.dance (); - } -}
/*
* In our writing program, we seldom write the code to death, for example, there will be daughter class
* and then in the wrapper function to invoke the object, perhaps the method of subclasses, here we explain this aspect of knowledge.
1 Abstract classparent{2 Abstract voidgrow ();3 }4 classSonextendsparent{5 voidgrow () {6System.out.println ("I grew up better than my father: Son");7 }8 voidPlay () {9System.out.println ("I Can Play");Ten } One } A classDaughterextendsparent{ - voidgrow () { -System.out.println ("I grew up better than my father: Daughter"); the } - voidDance () { -System.out.println ("I Can Dance"); - } + } - Public classTest { + Public Static voidMain (string[] args) { AParent p=NewSon (); at Show (p); -Parent p2=Newdaughter (); - Show (p2); - } - Public Static voidShow (Parent p) { - //now output the methods in the parent class in P.grow (); - //type judgment on the objects that have been transformed and then make the corresponding forced transformation to if(pinstanceofSon) { + //determine which class is on the top of the transformation object and then make the next transformation -Son s=(Son) p; the //calling a method in a subclass * S.play (); $}Else if(pinstanceofdaughter) {Panax NotoginsengDaughter D=(daughter) p; - d.dance (); the } + A } the}
Transformation and down-conversion in Java (object polymorphism)