In Java, it is possible that the parent class is forcibly converted to a subclass.

Source: Internet
Author: User

In Java, it is possible that the parent class is forcibly converted to a subclass.

Previously, the apprentice asked a question: in Java, can a parent class object be converted to a corresponding subclass object?

If it is possible, let's talk about this problem today. Let's look at the following code:

Package cn.com. hanbinit. test;/*** check whether the parent class can be strongly converted to a subclass * @ author icer **/public class ConvertPro extends Father {public static void main (String [] args) {Father father = new Father (); Father father1 = new ConvertPro (); ConvertPro son = new ConvertPro (); // ConvertPro son1 = (ConvertPro) new Father (); // son = (ConvertPro) father; son = (ConvertPro) father1 ;}/ *** parent class ** @ author icer **/class Father {private String name; public String getName () {return name;} public void setName (String name) {this. name = name ;}}

The two lines commented out by the code above will run incorrectly. according to the Code, only when the parent class object itself is new from the subclass can it be forcibly converted into a subclass object in the future.

The subclass inherits all the attributes and methods of the parent class. That is to say, the content of the subclass should be larger than that of the parent class. if a parent class is converted into a subclass in a normal environment, precision will be lost. however, if the parent class object itself uses

Subclass is new,It is similar to a person who is a son role. After installing a father for a while, the role can be converted back in the future. However, a father can never pretend to be a son..

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.