I'll talk to you today. Forced type conversions for Java reference types

Source: Internet
Author: User
Tags java reference

In fact, the basic type is also the existence of coercion type conversion, here is a simple mention. Generally, there are two types:

1, automatic type conversion, also known as implicit type conversion, that is, the data range of small conversion to a large data range , the compiler automatically complete the type conversion, do not need us to write code

2, forced type conversion, also known as explicit type conversion, that is, the data range of large conversion to a small data range , the data will lose precision, strong turn also need to write code to implement, use need to be cautious

Let's take a look at the coercion type conversions for reference types:

There are also two kinds of: implicit and explicit

1, implicit strong turn, is the parent class refers to the object of the subclass , such as the Father class and the child class, we can write:

Father f = new Child ();

For subclasses and parent classes, we can understand that subclasses are inherited from the parent class, so the function is more than the parent class.

Popular understanding is the sub-class to the parent class, no problem!

It is important to note that the child object is still a child in the in-memory type

2, explicit strong turn, explicit strong transfer appears 2 kinds of situations:

① references to the parent class object to the subclass :

Father f = new Child ();

At this point child C = (child) F; The parent class is feasible, and it is understood that the reference to F is itself an object to the child class, so it is possible to cast F to child.

The reference to the ② parent class is directed to the parent class's own object:

Father f = new Father ();

At this point the child C = (child) F; The parent class is not feasible and the runtime throwsClassCastException异常,即类型不兼容

I'll talk to you today. Forced type conversions for Java reference types

Related Article

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.