Conversion between Java subclass and parent class

Source: Internet
Author: User

The parent class object cannot be converted to a subclass object, and the Child class can be converted to a parent class.
It can be converted because it is indeed.
It cannot be switched because it is not.

----------------------------------------------------------------------

B extends

A A = new B ();
B = (B);

Here, new B () itself is the object of the subclass. It just points to it by referencing a of the parent class!

Class

{
Public void print ()
{

System. Out. println ("A. func1 ");
}
}

 
Class B extends
{
Public void print ()
{
 
System. Out. println ("B. func1 ");
}
}

Sub-classes can appear as parent classes (A = new B ();), but they do things in their own way:. the output result of func1 () is "B. func1"
The parent class cannot appear as a subclass (B = new A ();) because a downward transformation exception is reported.

The forced conversion of Java is used when the subclass object is uploaded to the parent class and you need to retrieve the subclass object again, use the lower-Pass Method to forcibly replace the object with the subclass object. That is to say, the original object is a subclass at the beginning, but the specific type is lost during the upload.

Now you want to convert the parent class object into a subclass object. This is impossible. There is a class in each class to store the specific information of each class, this ensures that the most primitive class can be found during the upload and downstream operations of the class.
In structs, The actionfrom object is actually a subclass object, but it is uploaded to a reference of the parent class. Therefore, the class of this object stores the subclass information, forced conversion to subclass is acceptable. Like: Father A = new son (); son B = (son);

If you want to change father a = new father (); son B = (son), the former class stores subclass information (including methods, variables, and blocks), and the latter stores parent class information.
 

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.