How to convert the type of the parent class and subclass in Java

Source: Internet
Author: User

We often see this scenario in projects. To realize the polymorphism bound during java runtime, reference the parent class to the subclass object

For example

[Java]
Parent p = new Son ()
The advantage of this is that the Code is highly scalable and has low coupling. For example, if a method accepts the Parent parameter type, we can pass any subclass object that inherits the Parent type as the real parameter when calling the method. In this way, the runtime binding is realized.
However, in this case, we can only use p to call the method of the parent class, rather than the special method of the subclass. So if we want to call the special method of the subclass, we need to implement it through forced type conversion.

For example

[Java]
(Son) p). s1 () or Son s = (Son) p
This is the meaning of type conversion between parent class and Child class.
Another case is to direct the parent class reference to the parent class object, and then forcibly convert the parent class reference to the subclass reference.

For example

[Java]
Parent p = new Parent ();
On s = (Son) p;
Java developers think this is meaningless, so we cannot do this during the development process. JVM will encounter an exception in packet type conversion errors.

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.