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