Transformation and down-conversion in Java

Source: Internet
Author: User

The Java transformation problem is not complicated, just remember the word: The parent reference points to the subclass object.

What is a parent class reference to a subclass object, and listen to me slowly.

Start with 2 nouns: upward transformation (upcasting), downward transformation (downcasting).

For example: There are 2 classes, Father is the parent class, and the son class inherits from father.

Father f1 = new Son (); This is called upcasting (upward transformation)

Now the F1 reference points to a son object

son S1 = (son) F1; This is called downcasting (downward transformation)

Now F1 still point to son object

A 2nd example:

Father F2 = new Father ();

Son s2 = (son) F2; Error, subclass reference cannot point to parent class object

You might ask, in the 1th example: son s1 = (son) F1; ask what is right.

Very simple because F1 points to a subclass object, Father f1 = new Son (); The subclass S1 Reference can of course point to the child class object.

The F2 is passed to a Father object, Father f2 = new Father (); The subclass S1 reference cannot point to the parent class object.

Summarize:

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

2. The target class object is directly assigned to the parent class reference called upcasting, which transforms upward without casting.

such as: Father F1 = new Son ();

3. Assign the parent class reference to the subclass object to the subclass reference called down Transformation (downcasting), to cast.

For example, F1 is a parent class reference to a subclass object. Assign F1 to the subclass reference S1 that son S1 = (son) F1;

Where the F1 front (Son) must be added, cast.

Transformation and down-conversion in Java

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.