Shift up and down

Source: Internet
Author: User

The upward transformation is to convert other types of objects to type object, while downward transformation is the opposite.

Cases:

1  Public classTest {2    PrivateObject b;//Set Object type member variable3     PublicObject Getb () {4        returnb;5    }6     Public voidSetb (Object b) {7         This. B =b;8    }9     Public Static voidmain (String [] args) {TenTest test =NewTest (); OneTEST.SETB (NewBoolean (true));//Upward Transformation A System.out.println (Test.getb ()); -TEST.SETB (NewFloat (12.3)); -float f = (float) (TEST.GETB ());//Down Transformation the System.out.println (f); -TEST.SETB (NewFloat (12.3)); -Integer f1 = (integer) (Test.getb ());//downward transformation, throws an exception - System.out.println (F1); +         -    } +}

Operation Result:

True
12.3
Exception in thread "main" Java.lang.ClassCastException:java.lang.Float cannot is cast to Java.lang.Integer
At fanxing. Test.main (test.java:19)

In the above example, a private member variable B is defined in the test class, it is of type object type, and a corresponding set and get method is defined for it, and the new Boolean (True) object is used as the SETB () method parameter. Because the parameter type of the SETB () method is object, this allows for "upward transformation", and when the Getb () method is called, the object objects returned by the GETB () method are returned with the appropriate type, which is "down transformation", which is usually the problem because "the transition "Is safe, and the" down-transition "operation uses the wrong type, or if the operation is not performed, an exception occurs.

Shift up and down

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.