Java up and down transformation

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.