Java up and down transformation

Source: Internet
Author: User

It's not hard to learn how to move up and down, but why do you use it so much that I haven't figured it out many times? Do not understand the reason is usually the study of the example, and examples are generally relatively simple, no object between the call, is generally an object to call their own method.

First look at how to use the transformation.

To transform, there must be inheritance first. Inheritance is a mechanism of code reuse in object-oriented languages, which simply means that subclasses inherit non-private attributes from the parent class and can inherit methods, and the subclass can continue to extend its own properties and methods.

Transition up: The subclass object becomes the parent class, and the parent class can be an interface. Formula: Father f = new Son (); Father is the parent class or interface, and Son is a subclass.

Transition down: Parent class object to child class. Formula: son s = (son) F;

Example: Upward transformation

1  Packagemultistate;2 3  Public classHuman {4 5      Public voidsleep () {6System.out.println ("Human sleep ...");7     }8 9      Public Static voidMain (string[] args) {TenHuman h =NewMale ();//Upward Transformation One h.sleep (); AMale m =NewMale ();//Why do you have to move up? - m.sleep (); -         //H.speak (); This method cannot compile, error says human class does not have this method the     } - } -  - classMaleextendsHuman { + @Override -      Public voidsleep () { +System.out.println ("Male sleep ..."); A     } at  -      Public voidspeak () { -System.out.println ("I am Male"); -     } - } -  in classFemaleextendsHuman { - @Override to      Public voidsleep () { +System.out.println ("Female sleep ..."); -     } the  *      Public voidspeak () { $System.out.println ("I am Female");Panax Notoginseng     } -}
View Code

Note: Do not force the transformation upward. A reference to an upward transformation stepfather class is a property of the parent class, and if the subclass overrides a method of the parent class, the parent reference refers to the method of the child class, which is called dynamic binding. The Stepfather class reference cannot call the subclass's own method, that is, the parent class does not have a method of the child class, if the call cannot be compiled, such as the Speak method of the subclass.

Do you want to invoke the properties of the subclass? If you do not move down, you need to write getter methods to the required attributes.

Example:

 Packagemultistate; Public classHuman {String name= "Human";  PublicString GetName () {return  This. Name; }     Public voidsleep () {System.out.println ("Human sleep."); }     Public Static voidMain (string[] args) {Human h=NewMale ();//Upward TransformationSystem.out.println (H.getname ()); }}classMaleextendsHuman {String name= "Male";  PublicString GetName () {return  This. Name; } @Override Public voidsleep () {System.out.println ("Male sleep."); }     Public voidspeak () {System.out.println ("I am Male"); }}classFemaleextendsHuman {String name= "Female";  PublicString GetName () {return  This. Name; } @Override Public voidsleep () {System.out.println ("Female sleep."); }     Public voidspeak () {System.out.println ("I am Female"); }}
View Code

Methods that do not call subclass extensions, such as the Speak method, can only be transformed downward.

Example: Downward transformation

A downward transition requires security, and if the parent class refers to an object that is the parent class itself, it is unsafe in the process of downward transformation and compiles without errors, but java.lang.ClassCastException errors occur at run time. It can use instanceof to avoid errors such as the ability to move down, only the objects that have been transformed up first can continue to transform downward.

 Packagemultistate; Public classHuman { Public voidsleep () {System.out.println ("Human sleep."); }     Public Static voidMain (string[] args) {Human h=NewMale ();//Upward TransformationHuman H1 =NewHuman (); //H.speak (); The Speak method cannot be called when a downward transition is required. Male m =(Male) H;         M.speak (); /**Male m1 = (Male) H1;    M1.speak (); A run-time error occurs, so you can use instanceof to determine*/         if(H1instanceofMale) {Male M1=(Male) H1;                      M1.speak (); }    }}classMaleextendsHuman {@Override Public voidsleep () {System.out.println ("Male sleep."); }     Public voidspeak () {System.out.println ("I am Male"); }}

After half a day, the upward transformation can not have all the methods of the sub-class, but also downward transformation, that direct Son s = new Son (); Wouldn't it be convenient? I don't know if it's just me. To start learning transformation has this idea.

Finally, the reason is that my example is too simple to think about passing the object of the class to other functions.

Example: to reflect the benefits of upward transformation, save code.

 Packagemultistate; Public classHuman { Public voidsleep () {System.out.println ("Human sleep."); }        Public Static  voiddosleep (Human h) {h.sleep (); }//the arguments passed at this point are the parent class object, but passing the subclass object when actually called is the upward transformation.      Public Static voidMain (string[] args) {Human h=NewMale ();//Upward TransformationDosleep (NewMale ());//This anonymous subclass object, of course, should be used in the actual application of the above transformation formula, and then the subclass object is passed in, so that later in the transition, there is no downward transformation, so the direct use of anonymous class object. Dosleep (NewFemale ()); }}classMaleextendsHuman {@Override Public voidsleep () {System.out.println ("Male sleep."); }}classFemaleextendsHuman {@Override Public voidsleep () {System.out.println ("Female sleep."); }}

If you do not move up, you must write two dosleep functions, one to pass the male class object, and one to pass the female class object. This is still two sub-classes, if there are many subclasses, it is necessary to write many of the same functions, resulting in repetition.

Well, finally understand why the upward transformation, once the upward transformation, when the need to use the subclass of the method, the need for a downward transformation, that is why the downward transformation is resolved.

To summarize:

1, the object of the class directly assigned to the parent class reference called upcasting upward transformation, upward transformation without forced transformation.

such as Father father = new Son ();

2. Assign the parent reference of the child class object to the subclass reference called Downward Transformation (downcasting), to be forced to transition, to the downward transformation, must first be transformed in order to security can be judged by instanceof.

If father is a parent reference to a subclass object, assign father to the subclass reference son, son son = (son) father;

Where the Father Front (Son) must be added for casting.

3, Upcasting will lose the subclass unique method, but the subclass overriding the parent class method, the subclass method is valid, the upward transformation can only refer to the parent class object's property, to refer to the Subclass object property, then writes the Getter function.

4, the role of upward transformation, reduce duplication of code, the parent class as parameters, and sometimes sub-class as a parameter, is the use of upward transformation. This makes the code concise. Embodies the idea of Java abstract programming.

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.