Javase (v) Java objects up and down transformation

Source: Internet
Author: User

Today did a test of the topic, found himself still a lot of problems did not calm down to do. A lot of problems can be solved on their own but one is not read test instructions, the second is his heart too impatient. So this should be self-identification!

The transformation of an object is not complicated, and we remember a word: "The parent class refers to the subclass object."

Transformation of objects in Java into an upward transformation and a downward transformation

I. Upward transformation of objects

1.1. Definition

    The object that the subclass refers to is converted to a parent class type called upward transformation. In layman's words, a subclass object is converted to a parent class object. Here the parent object can be an interface

1.2. Explanation

For example, I have two classes, one is the parent class animal, the other is the bird class is a subclass.

Animal B = new Bird ();

This is the upcasting, the upward transformation. At this point B is executing a spoof bird object.

1.3. Example

 

PackageCom.zyh.test;PublicClassAnimal {PublicvoidEat () {System.out.println ("animal eating ....")); }}Class BirdExtendsanimal{PublicvoidEat () {System.out.println ("Bird eating ..."); }Publicvoid Fly () {System.out.println ("Bird flying ..." class main{public static void main (string[] args) { Animal B1 = new Bird (); B1.eat ();   B1.fly (), b while pointing to the subclass object, but lost the Fly method Dosleep (new Male ()); Dosleep (new Female ());} public static void Dosleep (Human h) {h.sleep ();}}          
Animal.java
PackageCom.zyh.test;PublicClassAnimal {PublicvoidEat () {System.out.println ("animal eating ....")); }}Class BirdExtendsanimal{PublicvoidEat () {System.out.println ("Bird eating ..."); }Publicvoid Fly () {System.out.println ("Bird flying ..." class main{public static void main (string[] args) { Animal B1 = new Bird (); B1.eat ();   B1.fly (), b while pointing to the subclass object, but lost the Fly method Dosleep (new Male ()); Dosleep (new Female ());} public static void Dosleep (Human h) {h.sleep ();}}          
Huamn

Attention:

Here's the upward transformation:

Animal B = new Bird ();

B.eat ();

The Eat method called here is a subclass. Because b actually points to the bird subclass, it calls the method of the subclass itself.

Remember that a reference to the parent class when you move up is lost in addition to other methods that are common to the parent class. In the example above, B cannot call the Fly method.

    When you move up, the parent class points to the subclass reference object and loses other methods that are common to the parent object, that is, during the transformation, the new methods of the subclass are lost, and at compile time, the system provides an error that the method cannot be found.

1.4, the advantages of upward transformation

public static void Dosleep (Human h) {
H.sleep ();
}

In this case , the parent class is the parameter, and sometimes the sub-class is used as the parameter, which is the use of upward transformation. This makes the code concise. Otherwise
If Dosleep takes a subclass object as a parameter, then how many subclasses will need to write the number of functions. This also embodies the idea of Java abstract programming.

Ii. downward transformation of objects

1.1. Definition

The parent class references an object that is converted to a subclass type to become a downward transformation

1.2. Explanation

son s = (son) F1;

This is the downcasting, the downward transformation.

1.3. Example

PackageCom.zyh.test;PublicClassperson {PublicvoidPlay () {System.out.println ("Person play ..."); }}Class BoyExtendsperson{PublicvoidPlay () {System.out.println ("Boy play ...")); } public void Run () {System.out.println ("Run play ...");}} class runmain{ public static void main (string[] args) {Person b = new Boy ();  Upward Transformation b.play (); System.out.println ("-------------------------"); Boy B1 = (boy) b; // downward Transformation b1.play (); B1.run ();}}             

Results:

    

In this program

Girl g1=new Mmgirl (); Upward transformation
G1.smile ();
Mmgirl mmg= (mmgirl) G1; Down transformation, compile and run without errors

The downward transformation here is safe. Because G1 points to a subclass object.

and
Girl g2=new Girl ();
Mmgirl mmg1= (mmgirl) G2; Unsafe down-conversion, compile error-free but run errors

Error running:

Exception in thread "main" Java.lang.ClassCastException:com.wensefu.other1.Girl
At Com.wensefu.other1.Main.main (girl.java:36)

So in the process of downward transformation, it should be noted that:

    Case one: If the object referenced by the parent class refers to a sub-class object that is pointed to, it is safe in the process of downward transformation. That is, compiling does not make mistakes.

Scenario Two: 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 like this.

Iii. Summary

1. The parent class reference can point to the subclass object, and the subclass reference cannot point to the parent class object.

2, 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 ();

3. Assign the parent reference of the child class object to the subclass reference called down Transformation (downcasting), to force the transformation.

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.

4,Upcasting will lose the subclass-specific methods, but subclasses overriding the method of the parent class, the subclass method is valid

5, 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.

Javase (v) Java objects 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.