Transition up: Subclass to Parent class
Father father1= new Son ();
Down Transformation: Parent class Rotor class
Son son = (son) new Father (); This is when the runtime will error
Father father1 = new Son (); Son son1 = (son) father1; It's not an error.
To convert a parent class to a subclass by writing a method
classFather {PrivateString name; PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } /*** Convert the current object to a subclass object * *@paramclazz Target Type *@returntarget Object*/ Public<textendsFather> T to (class<t>clazz) {T instance; Try{instance=clazz.newinstance (); } Catch(Exception e) {Throw NewIllegalArgumentException ("Failed to create" + clazz.getsimplename () + "instance.", E); } instance.setname ( This. GetName ()); returninstance; }}
Public classSonextendsFather {PrivateString age; PublicString getage () {returnAge ; } Public voidsetage (String age) { This. Age =Age ; } Public Static voidMain (string[] args) {//subclass to Parent class, parent class again rotor class// Father Father = new Son (); // son son = (son) father; //Parent Class Direct Rotor class// son son = (son) new Father ();//Error when running//parent class to direct rotor class by MethodFather Father =NewFather (); Son son= Father.to (Son.class); }}
Java up and down transformation